Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide element when another div is visible in window

Tags:

html

jquery

css

I need to toggle the class .hidden to my sticky menu when either the #pre-footer or #footer div is visible in the window.

I've been messing with jquery and scrollTop(); but can't seem to get it going. Any help would be appreciated

$(document).ready(function() {
    var $window = $(window);
  var tabwrap = $('.tab-wrap');
  var prefooter = $('#pre-footer');
  $window.on('scroll', function() {
    var scrollTop = $window.scrollTop();
    tabwrap.toggleClass('hidden', scrollTop > 300); /* Help! */
    /* .tabwrap should toggle class .hidden when #pre-footer and or #footer is visible in window */
  });
});

Fiddle so far: https://jsfiddle.net/gavinfriel/4tcjnoxp/5/

like image 510
Gavin Friel Avatar asked Nov 16 '25 22:11

Gavin Friel


1 Answers

So basically you want to toggle the class when the bottom of the viewport is aligned with the bottom of #pre-footer. So when the scrollTop value + height of the viewport is greater than the position of the top of pre-footer + height of #pre-footer

$(document).ready(function() {
  var $window = $(window);
  var tabwrap = $('.tab-wrap');
  var prefooter = $('#pre-footer');
  var prefooter_top = prefooter.offset().top;
  var prefooter_height = prefooter.height();
  var prefooter_bottom = prefooter_top + prefooter_height;
  console.log(prefooter_bottom);
  $window.on('scroll', function() {
    var scrollTop = $window.scrollTop();
    var viewport_height = $(window).height();
    var scrollTop_bottom = scrollTop + viewport_height;
    tabwrap.toggleClass('hidden', scrollTop_bottom > prefooter_bottom); 
  });
});
like image 93
Derek Nolan Avatar answered Nov 19 '25 13:11

Derek Nolan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!