jQuery - hide element upon scrolling down, show element when scroll up

0 votes
317 views
added Jun 23, 2022 in jQuery by lcjr First Warrant Officer (11,780 points)

  $(window).load(function() { 
  var headerM = $('.header-mobile-view'),
      navHeader = $('nav.nav-new.navbar-new');

  var downScroll = 0;

  if ($(window).width() < 768) {
    $(window).scroll(function(event){
        var scroll = $(this).scrollTop();
        if (scroll > downScroll){  
          // navHeader.hide();
          navHeader.removeClass('in').addClass('out');
          console.log('out!'); 
          // }
        } else { 
          // navHeader.show();
          navHeader.removeClass('out').addClass('in');
          console.log('in!');
        }
        downScroll = scroll;
    });
  }
  else {
    // do nothing 
  }

});

 

CSS

.navbar-new {
  @media (max-width: 768px) {
    // display: none;
    position: fixed; 
    transition: all .3s .2s ease-in-out;
    // bottom: -48px; 
    &.in, &.out {
      cursor: pointer; 
      transition: all .3s .2s ease-in-out;
    }
    &.in { 
      top: 0; 
    }
    &.out { 
      top: -71px; 
    }
  }  
}

 

HTML output

<!--When scroll down-->
<nav class="navbar-new out">


<!--When scroll up-->
<nav class="navbar-new in">
lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...