Is it possible to tell whether a scroll event was done by the browser or by the user? Specifically, when using the back button a browser may jump to the last known scroll position. If I bind to scroll event how can I tell whether this was caused by user or browser?
$(document).scroll( function(){
//who did this?!
});
I see three types of situations that cause scrolling in a browser.
- The user performs some action. For example, uses mousewheel, arrow keys, page up/down keys, home/end keys, clicks the scrollbar or drags its thumb.
- The browser scrolls automatically. For example, when using the back button in your browser it will jump to the last known scroll position automatically.
- Javascript scrolls. For example,
element.scrollTo(x,y).
Unfortunately, there is no direct way of telling that.
I would say if you can redesign your app so that it doesn’t depend on this type of flow, go for that.
If not, a workaround I can think of is to keep track of user initiated scrolls and check that to see if the scroll was triggered by the browser or by the user.
Here’s an example that I put together which does this pretty well (except for browsers where jQuery history has problems with).
You need to run this locally to be able to test it fully (jsFiddle/jsbin are not good fits as they iFrame the contents).
Here’s the test cases that I validated:
userScrollisfalseuserScrollbecomestrueuserScrollbecomesfalseuserScrollbecomesfalse;Notes:
event.keyCodesmay vary by OS, so you may have to change that appropriately.Hope this helps!