0

I know .scroll() detects scrolling but what if I want something to happen only when the user scrolls down or vice versa?

tripstar
  • 161
  • 1
  • 2
  • 11

1 Answers1

0

There is not a listener for this, but you can have a variable with last position scrolled and check against new one. So it would be something like this:

Keep a variable, say, last_scroll_position, and when you have a scroll, if last_scroll_position - current_position > 0, the user scrolled up, and down if it's less than 0.

For further reference:

Differentiate between scroll up/down in jquery?

Example:

<div style='height:10000px;'>

var last_scroll=0;
$(window).scroll(function() {
    var direction='none';
    var current_scroll=$(this).scrollTop();
    if(current_scroll < last_scroll) direction='up';
    else if(current_scroll > last_scroll) direction = 'down';
    last_scroll=current_scroll;
    console.log(direction)
});
Community
  • 1
  • 1
juvian
  • 15,875
  • 2
  • 37
  • 38
  • Thanks for answering my question. The logic behind this seems simple enough, the only problem I am having is capturing the value for last_scroll_position. I have a function that captures scrollTop so creating the variable for the current scroll position is pretty easy. Just can't wrap my head around how to capture the previous scroll position. – tripstar Apr 28 '14 at 14:17
  • @tripstar added a code example, hope it helps! – juvian Apr 28 '14 at 18:02