Search code examples
javascripteventsmousedownmouseup

How to do a work when mousedown until mouseup?


I'm making a simple player motion in Javascript canvas. (Up down left right)

I created 4 buttons on screen for mobile players. I used the following code for the buttons as I wanted to move the player until the button is released.

upBtn.addEventListeter('mousedown',()=>{
    let interval=setInterval(()=>{
        player.y--;
    }, 50);
    upBtn.addEventListener('mouseup',()=>{
        clearInterval(interval);
    });
});

The above code works perfectly when the buttons are clicked in a computer. But in mobile it is not working.

I also tried to use touchdown and touchup but it didn't work.

What changes should I make in the code to make it work in mobile also?

Thanks in advance


Solution

  • You're looking for touchstart and touchend

    function upFunc(event) {
        //prevents some devices to emulate the click event
        event.preventDefault();
        let interval=setInterval(()=>{
            player.y--;
        }, 50);
        upBtn.addEventListener('mouseup',downFunc);
        upBtn.addEventListener('touchend',downFunc);
    }
    
    function downFunc(e) {
        e.preventDefault();
        clearInterval(interval);
    }
    
    upBtn.addEventListeter('mousedown', upFunc);
    upBtn.addEventListeter('touchstart', upFunc);
    

    Note that to support both mouse and touch in vanilla js you'll have to add both event listeners.

    Also, some devices emulate the mouse events, so you can use preventDefault() to make sure your functions fires only once.