Prevent mousemove event on touch devices

Viewed 973

I'm listening to the mousemove event to give a button a nice effect based on the mouse position. On mobile however, if I touch the button the event is fired aswell making the button jump to the position. I'd rather have the button ignore the event when it's done by touch but I'm struggling to understand how this can be achieved?

// The function is just a helper of mine (it ads addEventListener to the matched events
createEventListener('.hoverable', 'mousemove', function(e) {
  // stripped out some calculations for simplicity reasons
  const deltaX = 50;
  const deltaY = 50;

  const transformString = `translate3d(${deltaX}px, ${deltaY}px, 0)`;

  this.style.mozTransform = transformString;
  this.style.webkitTransform = transformString;
  this.style.transform = transformString;
});
1 Answers

You could possibly add the CSS style: touch-action to your elements.

style="touch-action: none;"

or maybe add/remove events and cancel the action of that event:

So the order of events fired is: 1) touchstart 2) touchmove 3) touchend 4) mousemove 5) mousedown 6) mouseup 7) click.

Maybe something like this:

function handleTouch(e) {
  e.preventDefault();
}
document.getElementsByClassName("hoverable").addEventListener('touchstart', handleTouch, false);

document.getElementsByClassName("hoverable").removeEventListener('touchstart', handleTouch);
Related