0

Here is my jQuery code for removing sticky class while scrolling down.

$(window).scroll(function (e) {
    if ($('.main_form_wrapper').length != 0) {
        var window_scroll = $(window).scrollTop();
        console.log(window_scroll, "window scroll")
        var bottom_position = window_scroll + $('.main_form_wrapper').outerHeight(true);
        console.log(bottom_position, "form_position for footer")
        var form_top_offset = $('.main_form_wrapper').offset().top;
        console.log(form_top_offset, "form top offset")
        var footer_top_offset = $('.top_footer').offset().top;
        console.log(footer_top_offset,"footer top offset")
        if (window_scroll > form_top_offset &&  bottom_position < footer_top_offset) {
            $(".main_form_wrapper").addClass('sticky'); 
        } else {
            console.log('here')
            $(".main_form_wrapper").removeClass('sticky');  
        }
    }
});

please help anyone knows about it.

Shagun1390
  • 35
  • 1
  • 8
  • Can you show the HTML please? Without it, we can not guess the reason of not working. – Himanshu Upadhyay Dec 06 '17 at 06:53
  • there is lot off html code but i have a form in right side which needs to be fixed while scrolling up and once footer is appeared then sticky class should removed but in this case its not working. – Shagun1390 Dec 06 '17 at 06:59

1 Answers1

1

It's for 95% a duplicate of Detecting scroll direction

I took the time to create an example for you. I think the main point you where missing is you need to store the last scroll position to know if user is scrolling up or down the page. As simple as this:

var lastScrollTop = 0;
var theWrap = $('.wrap');
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
       // downscroll code
       theWrap.removeClass('sticky');
   } else {
      // upscroll code
       theWrap.addClass('sticky');
   }
   lastScrollTop = st;
});
.wrap {
  width: 100px;
  height: 2000px;
  background-color: orange;
}
.wrap.sticky {
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap sticky">

</div>
caramba
  • 21,963
  • 19
  • 86
  • 127