Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect whether scroll events are fired *only once* like on touch devices?

iOS devices (and likely Android ones) have a different scrolling behavior: The scroll event is only fired once after the entire scroll is done.

How do I detect whether the browser behaves this way?

I could use window.Touch or Modernizr.touch but they don't tell me anything about the scroll behavior, it would be like asking if someone is French to understand whether they like croissants, right? :)

like image 832
fregante Avatar asked Dec 05 '25 23:12

fregante


1 Answers

I think you're right about the detection because there will be some devices that will support both touch and mouse behaviors (like Windows 8 tablets), some will only support touch (phones) and some will only support mouse (desktops). Because of that, I don't think you can conclusively say that a device only has one behavior as some could have both.

Assuming that what you're really trying to do is to figure out whether you should respond immediately to every scroll event or whether you should use a short delay to see where the scroll destination ends up, then you could code a hybrid effect that could work well in either case.

var lastScroll = new Date();
var scrollTimer;
window.onscroll = function(e) {

    function doScroll(e) {
        // your scroll logic here
    }

    // clear any pending timer
    if (scrollTimer) {
        clearTimeout(scrollTimer);
        scrollTimer = null;
    }

    var now = new Date();
    // see if we are getting repeated scroll events
    if (now - lastScroll < 500){
        scrollTimer = setTimeout(function() {
            scrollTimer = null;
            doScroll(e);
        }, 1000);
    } else {
        // last scroll event was awhile ago, so process the first one we get
        doScroll(e);
    }
    lastScroll = now;
};

doScroll() would be your scroll processing logic.

This gets you a hybrid approach. It always fires on the first scroll event that arrives when there hasn't recently been a scroll event. If there are a series of scroll events, then it fires on the first one and then waits until they stop for a second.

There are two numbers that you may want to tweak. The first determines how close scroll events must be to consider them rapid fire from the same user action (current set to 500ms). The second determines how long you wait until you process the current scroll position and assume that the user stopped moving the scrollbar (currently set to 1s).

like image 108
jfriend00 Avatar answered Dec 07 '25 11:12

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!