0

I'm trying to create a drag-and-drop application using vanilla JS.

Example:  https://codepen.io/dever52/pen/MWrJxrL

However, this only works with a mouse. So i can't drag the element on a touch-device.

I've tried using the ontouchstart and ontouchend event to be able to use it on touch devices, but this doesn't work (see comments in the codepen) as expected. Is there a way how to make this work for touch devices?

dever52
  • 24
  • 2
  • 6
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Mar 25 '22 at 13:18

1 Answers1

0

Maybe this answer can help you -> html5 drag and drop FOR MOBILE

Most mobile devices do not listen to the drag events that are bound to the DOM. I would recommend using the touchmove event and the events that go along with with it. It would look something like:

I think these event listeners can help you

  var el = document.getElementById('drag');

  el.addEventListener("touchstart", handleStart, false);
  el.addEventListener("touchend", handleEnd, false);
  el.addEventListener("touchcancel", handleCancel, false);
  el.addEventListener("touchleave", handleEnd, false);
  el.addEventListener("touchmove", handleMove, false);
Or Nakash
  • 1,345
  • 1
  • 9
  • 22
  • Thanks for the answer. But the dragging doesn't start if I use the same eventhandler for mousedown and touchstart. How do I have to use handleStart for touch? – dever52 Mar 25 '22 at 13:51
  • what if we have a list of items. how can we listen to each element's event? – Najam Us Saqib Dec 21 '22 at 11:35