Search code examples
javascriptscrolltouchslide

scrollIntoView not executed in touch event listener


I'm trying to make a vertical slide, it works on desktop with wheel event but the scrollIntoView methode doesn't get executed in a touch event listener.

Here is the code

let startClientY, endClientY;
    page.addEventListener("touchstart", (event) => {
        startClientY = event.touches[0].pageY;
    }, false);

    page.addEventListener("touchmove", (event) => {
        endClientY = event.touches[0].pageY;
    }, false);

    page.addEventListener("touchend", (event) => {
        let diff = startClientY - endClientY;
        if (diff < -35) {
            if( i !== 0 ) {
                slides[i - 1].scrollIntoView({
                    behavior: "smooth", block: "start"
                });
                i--;
                console.log('scroll top'); // this code is executed as well
            }
        } else if (diff > 35) {
            if( i < slides.length -1) {
                slides[i + 1].scrollIntoView({
                    behavior: "smooth", block: "start"
                });
                i++;
                console.log('scroll down'); // this code is executed
            }
        }
        startClientY = undefined;
        endClientY = undefined;
    }, false);

The weird point is that the console logs inside the conditions are executed and the scrollIntoView method works outside the eventListeners

What am I missing ?


Solution

  • The problem comes from scrollIntoView behavior option inside a touch event listener, I've found another way to achieve what I want.

    let slideHeight = page.offsetHeight;
    page.addEventListener("touchstart", function (event) {
    startClientY = event.touches[0].pageY;
    }, {
        capture: true,
        passive: true
    });
    
    page.addEventListener("touchmove", function (event) {
        endClientY = event.touches[0].pageY;
    }, {
        capture: true,
        passive: true
    });
    
    page.addEventListener("touchend", (event) => {
        let diff = startClientY - endClientY;
        if (diff < -35) {
            if (i !== 0) {
                page.scrollBy(0, -slideHeight);
                i--;
            }
        } else if (diff > 35) {
            if (i < slides.length - 1) {
                page.scrollBy(0, slideHeight);
                i++;
            }
        }
        startClientY = undefined;
        endClientY = undefined;
    }, {
        capture: true,
        passive: true
    });
    

    Where page variable are my slides Hope it helps !