Sunday, 1 January 2023

window.scrollTo(x, y) is not working in mobile iOS

Trying to create a webpage that can

  1. move screen to the RIGHT while scrolling UP
  2. move screen to the LEFT while scrolling DOWN

I used the function of window.scrollTo for moving the screen. It works perfect in decktop browser and the desktop Chrome's mobile view. But, the function is not working in mobile even iOS Safari or iOS Chrome. Tried the setTimeout, but still not work. Any suggestions?

Below is the simplified codes that has the same issue.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<body style="margin: 0px; height: 100%; overflow: hidden;"> <!-- disable desktop scrolling -->
    <img style="width: 300%;" src="https://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg">
</body>

<script type="text/javascript">

    // Mobile
    document.body.addEventListener('touchmove', function(e){ 
        handleTouchMove(e);
        
        e.preventDefault(); // disable mobile user interaction
    }, { passive: false });

    var currentX = 0;

    function scrolling(isUp) {
        var movingBy = 10;
        // backward
        if (isUp) {
            currentX -= Math.min(movingBy, currentX);
        // forward
        } else {
            currentX += Math.min(movingBy, $(window).width() * 2 - currentX);
        }
        window.scrollTo(currentX, 0);
    }

    document.addEventListener('touchstart', handleTouchStart, false);  

    var xDown = null;                                                        
    var yDown = null;                                               
                                                                             
    function handleTouchStart(evt) {
        var touches = evt.touches || evt.originalEvent.touches;
        const firstTouch = touches[0];                                      
        xDown = firstTouch.clientX;                                      
        yDown = firstTouch.clientY;                                      
    };                                                
                                                                             
    function handleTouchMove(evt) {
        var xUp = evt.touches[0].clientX;                                    
        var yUp = evt.touches[0].clientY;

        var xDiff = xDown - xUp;
        var yDiff = yDown - yUp;
                                                                             
        if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {     
            // left and right            
        } else {
            // up and down
            scrolling(yDiff <= 0);                                                           
        }

        xDown = xUp;
        yDown = yUp;                                             
    };

    // desktop
    ...
</script>


from window.scrollTo(x, y) is not working in mobile iOS

No comments:

Post a Comment