It is known that scroll
event could be fired up by using mouse-wheel, clicking on scrollbar arrows or dynamically with window.scrollTo(left, top)
function.
Is it possible to determine what caused the scroll
event to fire up? Whether it was user intervention or JS code?
The scroll event occurs when the user scrolls in the specified element. The scroll event works for all scrollable elements and the window object (browser window). The scroll() method triggers the scroll event, or attaches a function to run when a scroll event occurs.
javascript - scrollIntoView does not trigger mousewheel nor scroll event in Angular - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.
When the page scroll happens, compare the previous scrollY value with the current scrollY . If the current value is greater than the old value, then the scroll direction is downwards. Otherwise, the scroll direction is upwards. Update the current scroll position to the variable.
I don't think you can determine what caused the scrolling. The scroll event only indicates that the window is scrolling, not why it's scrolling.
But perhaps you suspend the scroll event listener or set a flag before calling window.scrollTo()
from your code. Here in Safari, if you use scrollTo()
, the scroll event only fires once regardless of how much you scroll, so you could conceivably do something like this:
// somewhere in your code...
isCodedScrollEvent = true;
window.scrollTo(0, 200);
// elsewhere in your code...
function scrollListener(event) {
if( isCodedScrollEvent ) {
// event was caused by code, so handle it differently
// and then flip the flag back to false, so the next
// will be handled normally again
isCodedScrollEvent = false;
} else {
// event was caused by user
}
}
It ain't pretty, but it ought to work
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