0

I am trying to remove fixed class once user start scroll the page from the bottom of the window. Below is the code I have written. But it is working once the scroll bar reaches the top of the page

$(window).scroll(function() {
  if ($(this).scrollTop() > 1){
    $('.sticky-header').addClass('fixed');
  } else{
    $('.sticky-header').removeClass('fixed');
  }
});
PDSSandeep
  • 179
  • 10
  • Can you be a bit more clear in what you want ? Do you remove `fixed` class when user has reached the very bottom of the page and then starts scrolling up ? Or whenever the user scrolls up ? or something else ? – Gabriele Petrioli Feb 26 '19 at 13:41
  • Possible duplicate of [Remove class when bottom of div reaches viewport bottom](https://stackoverflow.com/questions/35174157/remove-class-when-bottom-of-div-reaches-viewport-bottom) – Daniel Smith Feb 26 '19 at 13:42
  • @Gabriele Petrioli : Whenever user starts scrolls up. I am trying to remove the fixed calss – PDSSandeep Feb 26 '19 at 13:43
  • for me I think `1` its too small to noticed .. try to change `1` with `$('.sticky-header').outerHeight(true)` or use [How can I determine the direction of a jQuery scroll event?](https://stackoverflow.com/questions/4326845/how-can-i-determine-the-direction-of-a-jquery-scroll-event) – Mohamed-Yousef Feb 26 '19 at 13:44

1 Answers1

0

You need to keep track of the previous scroll position so you know if the scroll direction is up or down.

var lastScroll = 0;

$(window).scroll(function() {
  var scrollTop = $(this).scrollTop();
  if (scrollTop == 0 || scrollTop < lastScroll) {
    $('.sticky-header').removeClass('fixed');
  } else {
    $('.sticky-header').addClass('fixed');
  }
  lastScroll = scrollTop;
}).triggerHandler('scroll');
.sticky-header {
  min-height: 500vh;
  border: 1em solid #ccc;
}

.sticky-header:before {
  top: 2em;
  left: 2em;
  padding: 1em;
  background: #eee;
  border: 1px solid #999;
  position: fixed;
  content: 'No fixed class';
}

.sticky-header.fixed:before {
  content: 'With fixed class';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<div class="sticky-header"></div>
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317