Skip to content
Advertisement

What is the equivalent of draggable: true/false for mobile touch events?

I have a drag-and-drop game that I built with JavaScript. Once an element is dragged into a certain area, I don’t want the user to be able to pick it up to drag it again. The draggable element is an image with a draggable: true property and some absolute value x-y positions, like this:

<img draggable="true" src="images/galleon.svg" style="position: absolute; left: 400px; top: 500px; />

After dragging (on the drop event for desktop, and touchend event for mobile), if the new x-coordinate (left property) is greater than “600”, I use JavaScript to change the image’s draggable property to false:

function moveDrop(e)
  image = e.target;
  if (
    image.style.left > "600") {
    image.setAttribute("draggable", "false");
  }

This works great on desktop. Once I drop the image anywhere past the 600px mark, I cannot click and drag it again.

However, it doesn’t work on mobile devices. I can still touch and drag the image again even if its new x-coordinate is greater than 600. Is there a one-liner I can add to the code above that will make the image “unresponsive” to future touch events, similar to draggable: false?

I tried adding an “if” statement to the touchstart event, hoping that the touchstart and touchmove functions would run only if the left value was less than 600. However, this made it so that I could drag the image up to 600, and then it would not let me continue dragging past 600 at all (the user should be able to drag up to 900 if they want).

I can provide the full code if necessary, but I am hoping that there will be a simple fix I can add into the touchend function instead, that will prevent future dragging on mobile.

Advertisement

Answer

Figured it out. I was able to prevent future touch events on an element if I added the CSS style pointer-events: none; to my touchend function, like this:

function moveDrop(e)
  image = e.target;
  if (
    image.style.left > "600") {
    image.style.pointerEvents = "none";
  }
Advertisement