HTML Drag and Drop on mobile (touchscreen screens)

Asked

Viewed 543 times

2

I’m thinking of making a panel using the features of Drag and Drop of HTML.

Example taken from w3schools

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}
div {
  width: 50px;
  height: 50px;
  padding: 10px;
  border: 1px solid #aaaaaa;
}
<html>
<head></head>
<body>

  <p>Arraste para o retângulo:</p>

  <div ondrop="drop(event)" ondragover="allowDrop(event)"></div>
  <img id="drag1" src="https://i.stack.imgur.com/uwI5h.png?s=48&g=1" draggable="true" ondragstart="drag(event)" width="50" height="50">

</body>
</html>


I wonder, how do I make this feature functional when it is opened on a mobile phone (or other touchscreen), because the "click" is different:

  • If I touch and drop, it would be a click
  • If I touch and hold, open the options

2 answers

3


I already had this problem and ended up using this solution: http://bernardo-castilho.github.io/DragDropTouch/

Bernardo Castilho’s script overwrites the events and makes them compatible with touch, can solve your problem.

jQuery also has a solution, but as you posted the code in pure javascript, I think this solution is more in line with what you are looking for.

Here the js file: Dragdroptouch.js

0

I recommend using Sortable:

  • Rubaxa/Sortable This guy is a plugin that uses native features for responsive drag and drop, it can be implemented with any CSS framework

Browser other questions tagged

You are not signed in. Login or sign up in order to post.