Determine what triggered the scroll event to fire

It is known that the scroll event can be triggered using the mouse wheel, clicking on the arrows of the scroll bar, or dynamically using the window.scrollTo(left, top) function.

Is it possible to determine what caused the scroll event to fire? Was this user intervention or JS code?

+6
source share
1 answer

I don’t think you can determine what caused the scroll. The scroll event indicates only the scrolling of the window, and not its scrolling.

But maybe you are pausing the scroll event listener or setting a flag before calling window.scrollTo() from your code. Here in Safari, if you use scrollTo() , the scroll event fires only once no matter how much you scroll, so you could 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 is not very, but it should work

+5
source

Source: https://habr.com/ru/post/894624/


All Articles