Search code examples
javascriptswipetouch-event

Detect screen moving with JS after user has swiped it and ended the touch


I have a scrollable html element, which is wider than screen. And there is mini scroll map to show scroll position.

On touch devices, when user makes a swipe move and then ends the touch, element continues scrolling for some time. How can I detect this scrolling with javascript to renew mini-scroll map?


Solution

  • I dont know of any native browser API that tells you the end of a scroll event. In our project we found a workaround that fits for all our usecases:

    You can listen for the scroll event and detect the end of the scrolling by a timeout timer.

    const scrollElement = document.getElementById("scrollcontainer");
    const scrollEndTime = 200 // time until callback fires when no scroll reaches
    
    let scrollEndTimeout = null;
    
    // Callback that fires when your scroll end has reached
    function scrollEndCallback() {
        // Do whatever you want in here
        console.log("ScrollEnd")
    }
    
    scrollElement.addEventListener('scroll', () => {
        if (scrollEndTimeout !== null) {
            // clears the previous timeout that has been set in the scorll
            clearTimeout(scrollEndTimeout);
        }
    
        // in every scroll set a new timeout that gets cleared when the next scroll event appears or fires when no other reaches
        scrollEndTimeout = setTimeout(() => {
            scrollEndCallback();
        }, scrollEndTime);
    });
    <div id="scrollcontainer" style="height:120px;width:120px;border:1px solid #ccc;font:16px/26px Georgia, Garamond, Serif;overflow:auto;">
    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
    </div>

    To debug (in chrome) press F12 and press "Toggle device toolbar" or press the shortcut within the console "Ctrl + Shift + M". This enters mobile mode and you can scroll.