I have this code for an HTML/CSS/JS Drag and Drop but it doesn't work on mobile. I would like to use the touchmove, touchstart, and similar events to solve this problem. From what I understand, you need both the drag events and the touch events in order for it to work on desktop AND mobile? I would also like to avoid using jQuery if possible. Nothing I have found online has had anything useful about making the drag and drop work for desktop AND mobile. How do I make it so it works on desktop and mobile too? Thanks in advance!
Edit: The proposed duplicates linked in the comments are not helpful and does not explain well how to implement the touch events into my code. It says they exist but not how to use them. The proposed duplicate just says "do the same for the rest of the elements" and I don't understand what that means.
<script>
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");
var nodeCopy = document.getElementById(data);
if (nodeCopy.classList.contains('insideBox')){
nodeCopy.setAttribute("style", "position:absolute; left:"+ ev.x +"px;top:"+ ev.y+"px;transform:translate(-"+nodeCopy.width/2+"px,-"+nodeCopy.height/2+"px)");
}
else{
nodeCopy=nodeCopy.cloneNode(true)
nodeCopy.classList.add("insideBox");
nodeCopy.id = "newId"+Math.random(100);
nodeCopy.setAttribute("style", "position:absolute; left:"+ ev.x +"px;top:"+ ev.y+"px;transform:translate(-"+nodeCopy.width/2+"px,-"+nodeCopy.height/2+"px)");
ev.target.appendChild(nodeCopy);
}
}
</script>
<style>
*{
margin:0;
padding:0;
}
.box {
display: block;
height: 300px;
width: 300px;
background-color: red;
}
</style>
<!--HTML-->
<span class="box" ondrop="drop(event)" ondragover="allowDrop(event)"></span>
<br />
<div id="picture" ondrop="drop(event)">
<img src="https://www.w3schools.com/html/img_w3slogo.gif" draggable="true" ondragstart="drag(event)" id="drag1" width="88" height="31">
</div>
<!--/HTML-->
Tryit: https://www.w3schools.com/code/tryit.asp?filename=GC15DE2JBSWV