Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine what caused scroll event to fire up

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?

like image 986
ritmas Avatar asked Aug 09 '11 11:08

ritmas


People also ask

What triggers a scroll event?

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.

Does scrollIntoView trigger scroll event?

javascript - scrollIntoView does not trigger mousewheel nor scroll event in Angular - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

How do you know if scroll is up or down?

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.


1 Answers

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

like image 165
Flambino Avatar answered Sep 21 '22 16:09

Flambino