skyisred
skyisred

Reputation: 7105

Distinguish between automatic browser scroll and user scroll

When you scroll to the middle of the page and then refresh it, the browser will automatically scroll to the position you were on. I need to be able to differentiate between this automatic scroll and user scroll and attach different events to them.

I'm currently using

window.addEventListener('scroll', function(e) {});

to listen to the scroll event, but it gets triggered in both user and automatic scrolls.

Is there a way to tell between the two?

PS the suggested answer to similar question only uses mousewheel as an indication of user scroll, but if the user uses mouse to pull the scroll, it will fail

Upvotes: 6

Views: 3164

Answers (2)

Joyce Lee
Joyce Lee

Reputation: 386

As Manohar previously mentioned, you can use some combination of an onscroll event and an onwheel event. onscroll runs on all scroll events, whenever the content is interacted with. onwheel will run on mouse or trackpad scrolls, but not arrow scrolling. It's also worth mentioning that onwheel is not guaranteed to trigger an onscroll event, depending on the context. There's more detail provided in its documentation.

There's another similar question here with some additional suggestions on redesigning your app, while setting some boolean flags that can help determine who (computer or real user) is initiating the scroll.

Upvotes: 1

Manohar Reddy Poreddy
Manohar Reddy Poreddy

Reputation: 27515

If you have two flags for both events, will that work?

I don't have a mouse to test this in whole unfortunately.

Try this fiddle

window.addEventListener( 'load', function() {
    var mousewheel = 0;
    var scroll = 0;

    window.addEventListener( 'scroll', function(e) {
        mousewheel = 0;
        scroll = 1;
        alert("mousewheel: " + mousewheel + ", scroll: " + scroll);
    }, false);

    window.addEventListener("mousewheel", function(e) {
        mousewheel = 1;
        scroll = 0;
        alert("mousewheel: " + mousewheel + ", scroll: " + scroll);
    }, false);

}, false);

Upvotes: 1

Related Questions