3

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

skyisred
  • 6,855
  • 6
  • 37
  • 54
  • 1
    possible duplicate of [How can I differentiate a manual scroll (via mousewheel/scrollbar) from a Javascript/jQuery scroll?](http://stackoverflow.com/questions/2834667/how-can-i-differentiate-a-manual-scroll-via-mousewheel-scrollbar-from-a-javasc) – TheSD Jul 28 '15 at 21:47
  • 1
    he 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 – skyisred Jul 28 '15 at 22:26

2 Answers2

1

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);
Strider
  • 3,539
  • 5
  • 32
  • 60
Manohar Reddy Poreddy
  • 25,399
  • 9
  • 157
  • 140
1

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.

Joyce Lee
  • 378
  • 3
  • 9