37

How do I detect horizontal scrolling with jQuery?

This will get all scrolls:

$(window).scroll(function () {
    alert('in');
});

I want just the horizontal one.

Praveen
  • 55,303
  • 33
  • 133
  • 164
Aharon Muallem
  • 1,143
  • 3
  • 13
  • 20

4 Answers4

45

This seems to work.

var lastScrollLeft = 0;
$(window).scroll(function() {
    var documentScrollLeft = $(document).scrollLeft();
    if (lastScrollLeft != documentScrollLeft) {
        console.log('scroll x');
        lastScrollLeft = documentScrollLeft;
    }
});

jsFiddle.

alex
  • 479,566
  • 201
  • 878
  • 984
  • Why do we need the .scroll(); at the end? – Aharon Muallem Aug 16 '11 at 11:46
  • @Aharon That was the appendix of my previous incarnation. It is unnecessary now and I will update my answer :) – alex Aug 16 '11 at 12:48
  • This only increments the value. How i can increment it when going right and decrement it when going left do you know? Thanks in advance. – Jonathan Calb Oct 01 '12 at 22:20
  • 1
    Solved it! [link](http://forrst.com/posts/jQuery_Determine_Scroll_Direction-LLJ). For horizontal only change .scrollTop() for .scrollLeft() and ready to go! Hope helps somebody. – Jonathan Calb Oct 01 '12 at 22:43
  • 1
    Can you tell me how can I detect end of the scrolling in a div. Like we can detect that user reach to the bottom end of the scrolling using scrollTop and scrollHeight but how to detect same in horizontal? – Jay Shukla Apr 17 '15 at 10:48
  • @JayShukla `scrollLeft` and `scrollWidth` I would guess. – alex Apr 19 '15 at 10:22
7

An update that shows direction left or right in a horizontal scroll based on code above:

var lastPos = 0;
$(window).scroll(function() {
    var currPos = $(document).scrollLeft();

    if (lastPos < currPos) {
        console.log('scroll right');
    } 
    if (lastPos > currPos) 
    {
        console.log('scroll left');
    }

    lastPos = currPos;
});

Test it at http://jsfiddle.net/EsPk7/7/

dunderwood
  • 579
  • 5
  • 5
4

dunderwood's jsFiddle link didn't actually contain his code. I've forked his jsFiddle with what a mixture of what he posted here and what's on the jsFiddle:

var lastPos = 0;
$(window).scroll(function() {
    var currPos = $(document).scrollLeft();

    if (lastPos < currPos) {
        $('#current').html('Right');
    }
    if (lastPos > currPos) {
        $('#current').html('Left');
    }

    lastPos = currPos;
});

http://jsfiddle.net/kuVK8/

dantiston
  • 5,161
  • 2
  • 26
  • 30
  • There is have a little problem. When you go up/or down, writing right and left. Is there any solution? – Rys Mar 30 '17 at 01:26
0
window.onresize = function() { 
    if ( $("div").outerWidth() < $("div").get(0).scrollWidth ) {
        console.log("foo bar scrollbar");
    } else {
        console.log(" no scrolling ");
    }
};
maxisme
  • 3,974
  • 9
  • 47
  • 97
mahtab
  • 1