18

I have found some great ways to check for where the scroll bar is using jquery, but I was wondering if you can differentiate whether or not the user scrolled up or down?

Hanna
  • 10,315
  • 11
  • 56
  • 89
  • 1
    I know this is old, but: http://stackoverflow.com/questions/4326845/how-can-i-determine-the-direction-of-a-jquery-scroll-event – Jacques Marais Jul 01 '16 at 12:05

6 Answers6

18
<script type='text/javascript'>
$(function(){

  var CurrentScroll = 0;
  $(window).scroll(function(event){

      var NextScroll = $(this).scrollTop();

      if (NextScroll > CurrentScroll){
         //write the codes related to down-ward scrolling here
      }
      else {
         //write the codes related to upward-scrolling here
      }

      CurrentScroll = NextScroll;  //Updates current scroll position
  });
});

Iman Sedighi
  • 7,624
  • 4
  • 48
  • 55
18

Check for the last state. 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.

Gabi Purcaru
  • 30,940
  • 9
  • 79
  • 95
  • Thank you. I knew I had to use a variable like that, the logic just wasn't registering in my brain. – Hanna Feb 14 '11 at 07:10
  • @Gabi Purcaru,if the `last_scroll_position` & `current_position` are same,the result will be `0`,in that time how to find ?????? – rynhe Mar 25 '13 at 09:54
  • @rynhe if `last_scroll_position - current_position == 0`, then the user didn't scroll at all – Gabi Purcaru Mar 25 '13 at 12:45
  • 4
    Just curious, why not just... `last_scroll_position < current_position //scroll down` and vice versa? Is there a reason to subtract and then compare rather than just compare? –  May 13 '14 at 20:30
  • Simple and effective solution. Thanks (Multzam in Ardeal :)) – Nahn Jan 17 '15 at 14:32
9

To differentiate between scroll up/down in jQuery, you could use:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){

    var evt = window.event || e //equalize event object     
    evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

    if(delta > 0) {
        //scroll up
    }
    else{
        //scroll down
    }   
});

This method also works in divs that have overflow:hidden.

I successfully tested it in FireFox, IE and Chrome.

Jordi van Duijn
  • 579
  • 1
  • 5
  • 3
4

Scroll Event

The scroll event behaves oddly in FF (it is fired a lot of times because of the smoothness scrolling) but it works.

Note: The scroll event actually is fired when dragging the scroll bar, using cursor keys or mousewheel.

//creates an element to print the scroll position
$("<p id='test'>").appendTo("body").css({
    padding: "5px 7px",
    background: "#e9e9e9",
    position: "fixed",
    bottom: "15px",
    left: "35px"
});

//binds the "scroll" event
$(window).scroll(function (e) {
    var target = e.currentTarget,
        $self = $(target),
        scrollTop = window.pageYOffset || target.scrollTop,
        lastScrollTop = $self.data("lastScrollTop") || 0,
        scrollHeight = target.scrollHeight || document.body.scrollHeight,
        scrollText = "";

    if (scrollTop > lastScrollTop) {
        scrollText = "<b>scroll down</b>";
    } else {
        scrollText = "<b>scroll up</b>";
    }

    $("#test").html(scrollText +
      "<br>innerHeight: " + $self.innerHeight() +
      "<br>scrollHeight: " + scrollHeight +
      "<br>scrollTop: " + scrollTop +
      "<br>lastScrollTop: " + lastScrollTop);

    if (scrollHeight - scrollTop === $self.innerHeight()) {
      console.log("► End of scroll");
    }

    //saves the current scrollTop
    $self.data("lastScrollTop", scrollTop);
});

Wheel Event

You also may take a look at MDN, it exposes a great information about the Wheel Event.

Note: The wheel event is fired only when using the mousewheel; cursor keys and dragging the scroll bar does not fire the event.

I read the document and the example: Listening to this event across browser
and after some tests with FF, IE, chrome, safari, I ended up with this snippet:

//creates an element to print the scroll position
$("<p id='test'>").appendTo("body").css({
    padding: "5px 7px",
    background: "#e9e9e9",
    position: "fixed",
    bottom: "15px",
    left: "15px"
});

//attach the "wheel" event if it is supported, otherwise "mousewheel" event is used
$("html").on(("onwheel" in document.createElement("div") ? "wheel" : "mousewheel"), function (e) {
    var evt = e.originalEvent || e;

    //this is what really matters
    var deltaY = evt.deltaY || (-1 / 40 * evt.wheelDelta), //wheel || mousewheel
        scrollTop = $(this).scrollTop() || $("body").scrollTop(), //fix safari
        scrollText = "";

    if (deltaY > 0) {
        scrollText = "<b>scroll down</b>";
    } else {
        scrollText = "<b>scroll up</b>";
    }

    //console.log("Event: ", evt);
    $("#test").html(scrollText +
      "<br>clientHeight: " + this.clientHeight +
      "<br>scrollHeight: " + this.scrollHeight +
      "<br>scrollTop: " + scrollTop +
      "<br>deltaY: " + deltaY);
});
jherax
  • 5,238
  • 5
  • 38
  • 50
4

Example for vanilla javascript:

var f = (function(){
    var oldPos = window.scrollY;
    function fu(e) {
        var newPos = window.scrollY;
        if (newPos>oldPos) {
            console.log('down');
        } else if(newPos<oldPos) {
            console.log('up');
        } else {
            console.log('same');
        }
        oldPos = newPos;
    }
    return fu;
})();
window.addEventListener('scroll',f);
2

There is a simple way to do it without global variables of any kind. MouseWheel event has a property explicitly specifying scrolling direction. Here's how to use it:

   $("#scroll_div").bind("mousewheel",function(ev) {
      var curScrollLeft = $(this).scrollLeft();
      $(this).scrollLeft(curScrollLeft + Math.round(ev.originalEvent.wheelDelta));
    });
monday
  • 319
  • 2
  • 12