How do I detect horizontal scrolling with jQuery?
This will get all scrolls:
$(window).scroll(function () { alert('in'); });
I want just the horizontal one.
The scrollTop() method sets or returns the vertical scrollbar position for the selected elements. Tip: When the scrollbar is on the top, the position is 0. When used to return the position: This method returns the vertical position of the scrollbar for the FIRST matched element.
The scrollLeft() method sets or returns the horizontal scrollbar position for the selected elements. Tip: When the scrollbar is on the far left side, the position is 0. When used to return the position: This method returns the horizontal position of the scrollbar for the FIRST matched element.
Using the devtools To find out which elements cause a horizontal scrollbar, you can use the devtools to delete elements one by one until the scrollbar disappears.
In jQuery, we can make any element tag move horizontally using the built-in function scrollLeft() function for scrolling the scrollbar horizontally according to either the position which is set as the parameter or without setting the position which would specify the position in pixel number of the scrollbar.
This seems to work.
var lastScrollLeft = 0; $(window).scroll(function() { var documentScrollLeft = $(document).scrollLeft(); if (lastScrollLeft != documentScrollLeft) { console.log('scroll x'); lastScrollLeft = documentScrollLeft; } });
jsFiddle.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With