Search code examples
javascripthtmltouch-event

Detect touch move event on mobile divices


I am working on detecting horizontal drag feature which would detect the changes in movement in X direction.Following is the code:

const myObject = document.getElementById("scroll-window");
play3D()
var a = 0
var b = 0
myObject.onpointerdown = (e) => {

    a = e.clientX;
    myObject.onpointermove = (e) => {

        b = e.clientX;
        var motionx = e.movementX
        if (e.movementX >=10){
            motionx = 10
        }
        moveX = b-a;
        if (moveX>5){
            console.log(moveX)
            setImage(+1);
            a = b;
        } else if (moveX<5){
             setImage(-1);
        }
        a = b;
    }
}
myObject.onpointerup = (e) => {
    moveX = 0;
    myObject.onpointermove = null;
}

This works for desktop, but it does not work for mobile divices. Can anyone please suggest me what can be done to achieve this ?


Solution

  • pointer[...] events do not apply to touch. For touch you want touch[...] events.

    myObject.addEventListener("touchstart", (e) => {
      ...
    });
    // touchstart, touchmove, touchend, touchcancel
    

    Other parts of the code is pretty much the same.

    Read more here: https://developer.mozilla.org/en-US/docs/Web/API/Touch_events/Using_Touch_Events


    As a sidenote, pointer[...] events have been obsoleted in favour of mouse[...] events. You may wish to switch to those.

    Read more here: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent


    Per OP's request, if you want the same action to happen on both events, just declare the event handler function explicitly, and pass it to addEventListener() two times. Something like this:

    function hdlr1(ev) {
      // Handle event here
    }
    myObject.addEventListener("touchstart", hdlr1);
    myObject.addEventListener("mousedown", hdlr1);
    ...
    

    However I personally do not recommend it in this case, since you may wish to give mouse and touch slightly different behaviours in the future. In addition, you should be careful to only use properties and functions common to mouse[...] and touch[...] events. I'm not going to explain polymorphism in this answer, but basically you should treat the event in this handler as a UIEvent, since UIEvent is the last common ancestor of MouseEvent and TouchEvent.