This question was already asked here a long time ago:
Detect jquery event trigger by user or call by code
But it has never been answered conclusively (or maybe I'm simply not able to search properly).
Is it possible to detect whether a scroll
event has been triggered by the user or by the jQuery animate
function?
I am trying to prevent the scroll
event to trigger itself while doing something like this:
$(document).scroll(function(){
$("html").stop(true);
var number = 400; //some other stuff is happening here
clearTimeout(tout);
tout = setTimeout(function(){
if(top == $(document).scrollTop()){
$("html").animate({
scrollTop: (number),
easing: "easeInQuad",
duration: 110
});
}
},120);
});
This code seems to be suitable:
$('#scroller').scroll(function(e) {
if (e.originalEvent) {
console.log('scroll happen manual scroll');
} else {
console.log('scroll happen by call');
}
});
But the originalEvent
object isn't able to detect the animate trigger properly.
Is there any other way to do this?
Maybe :animated
selector will help you:
$('#scroller').scroll(function(e) {
if ($(this).is(':animated')) {
console.log('scroll happen by animate');
} else if (e.originalEvent) {
// scroll happen manual scroll
console.log('scroll happen manual scroll');
} else {
// scroll happen by call
console.log('scroll happen by call');
}
});
Demo
I don't know how well this works with touch screen devices but this works for me on desktop at least
$(window).on('mousewheel', function(){
//code that will only fire on manual scroll input
});
$(window).scroll(function(){
//code that will fire on both mouse scroll and code based scroll
});
I don't think there is a way to only target the animated scroll (the accepted answer didn't work for me).
UPDATE: Warning!
Unfortunately, 'mousewheel'
doesn't seem to pick up on users who manually grab the scroll bar and drag it or users who use the scroll bar arrow buttons :(
This still works ok for touch screen devices as their swipes seem to count as mouse scrolls. This isn't a great solution for desktop users though.
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