2

My jQuery code shows a div when the user scrolls down past 44px and disappears when scrolling up past 44px. I only want to show the div when scrolling down not up.

$(document).ready(function() {
  $(window).scroll(function(e) {
    // Variable declaration for search container
    var $src = $('.main-div');

    // Variable declaration for position fixed
    var isPositionFixed = ($src.css('position') == 'fixed');

    // Scroll if statement for position scroll - Scroll down 
    if ($(this).scrollTop() > 44 && !isPositionFixed) {
      $src.css({
        'position': 'fixed',
        'top': '0'
      });
      $('.main-div').show();
    }

    // Scroll if statement for position scroll - Scroll up
    if ($(this).scrollTop() < 44 && isPositionFixed) {
      $src.css({
        'position': 'static',
        'top': '0'
      });
      $(".main-div").hide();
    }
  });
});
Sole
  • 3,100
  • 14
  • 58
  • 112
  • You can use javascript to tell which direction you are scrolling. I'd check these SO answers out: https://stackoverflow.com/questions/31223341/detecting-scroll-direction and https://stackoverflow.com/questions/7154967/how-to-detect-scroll-direction/33334461 – justDan Aug 27 '19 at 14:25
  • Thanks, some good solutions in there, can you put your comment as an answer and I can accept it – Sole Aug 27 '19 at 15:39

1 Answers1

4

Sole! Try this code, please.

$(document).ready(function() {
  var prevScrollTop = $(window).scrollTop()
  
  $(window).on('scroll', function(e) {
    // Variable declaration for search container
    var $src = $('.main-div');
    var currentScrollTop = $(this).scrollTop()

    if (currentScrollTop >= prevScrollTop && currentScrollTop > 44) {
      $src.css({
        'position': 'fixed',
        'top': '0'
      });
      $('.main-div').show(200);
    } else {
      $src.css({
        'position': 'static',
      });
      $(".main-div").hide();
    }
    
    prevScrollTop = currentScrollTop
  });
});
.container {
  height: 200vh;
}

.some-content {
  height: 50vh;
  background-color: #cecece;
  padding: 5px;
  text-align: center;
}

.main-div {
  height: 30px;
  background-color: green;
  left: 0;
  right: 0;
  color: #FFFFFF;
  padding: 5px;
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="some-content">Try to scroll down</div>
  <div class="main-div" style="display:none;">SOME FIXED HEADER ONLY ON SCROLL BOTTOM</div>
</div>
Evgeny Melnikov
  • 952
  • 7
  • 13