0

I got to animate a div when $('body').scrollTop() > 45

I need animate the same div when the user scrolls up. I tried this code, the first if works. How can I get the second conditional to work?

    if ($('body').scrollTop() > 45) {

        $('.my-div').animate({
            top:'-45px'
        }, 200);
    }         
    if (¿?user-scrolls-up¿?) {

        $('.my-div').animate({
            top:'0px'
        }, 200);
    } 
chefnelone
  • 189
  • 1
  • 4
  • 16
  • Save the scroll value to a variable on scroll. Compare to the previous scroll value. If previous > current then user has scrolled up. Or you could use a `setInterval`, comparing the last iteration intervals' scroll position to the current iteration – Zach Saucier Jan 17 '14 at 15:29
  • possible duplicate of [How to hide a Div when the scroll bar is moving with jQuery?](http://stackoverflow.com/questions/7390960/how-to-hide-a-div-when-the-scroll-bar-is-moving-with-jquery) – CRABOLO Jan 17 '14 at 15:31
  • @ZachSaucier thanks, got it working based in your comment. – chefnelone Jan 17 '14 at 15:41

1 Answers1

0

One way to do it would be to save the scroll value to a variable on scroll. Then you can compare that value to the previous scroll value. If previous > current then user has scrolled up.

Here is pseduo-code for that situation

var lastScroll = 0;
$(window).scroll(function() {
    var currentScroll = $(window).scrollTop();
    ... Your first if perhaps using currentScroll ...
    if(currentScroll < lastScroll) {
        $('.my-div').animate({
            top:'0px'
        }, 200);
    }
    lastScroll = currentScroll;
}

Or you could use a setInterval, comparing the last iteration intervals' scroll position to the current iteration

Zach Saucier
  • 24,871
  • 12
  • 85
  • 147