How can I test for sideways/horizontal scrolling in a browser window with Javascript/Jquery, and then perform an action when movement is detected?
Asked
Active
Viewed 75 times
0
-
Perfect answers: I wasn't finding those in google until you two posted these links. Is it better to search via the StackOverflow search bar than google? – Chain Aug 14 '18 at 19:54
2 Answers
1
You can bind to the window scroll
event and use the last scrollLeft position to determine if it has changed or not.
var lastPosition = 0,
doc = $(document),
win = $(window);
win.scroll(function() {
var scrollPosition = doc.scrollLeft();
if(lastPosition != scrollPosition) {
lastPosition = scrollPosition;
console.log('scroll left changed!');
}
});
.container {
border: 1px solid #000;
height: 50px;
width: 10000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
hello
<div>
Vanilla JS
var lastPosition = 0;
window.addEventListener('scroll', function(){
var scrollPosition = this.pageXOffset;
if(lastPosition != scrollPosition) {
lastPosition = scrollPosition;
console.log('scroll left changed!');
}
});

dysfunc
- 2,008
- 1
- 13
- 15
0