Some time ago I was struggling with drag and drop in web browsers on mobile devices. The default javascript events do not work on mobile. You can use only touch events.
In my case, I need to swap two images and also the IDs by doing drag and drop. Here an example:
div{
display:inline-block;
border:1px solid #0b79d0;
}
div, img{
width:120px;
height:120px;
}
<div id="1" ondragover="allowDrop(event)" ondrop="drop(event)" ondragenter="dragEnter(event)" ondragleave="dragLeave(event)" draggable="false">
<img id="a" draggable="true" ondragstart="dragStart(event)" src="https://static.webshopapp.com/shops/073933/files/156288269/345x345x1/artibalta-white-tiger.jpg"/>
</div>
<div id="2" ondragover="allowDrop(event)" ondrop="drop(event)" ondragenter="dragEnter(event)" ondragleave="dragLeave(event)" draggable="false">
<img id="b" draggable="true" ondragstart="dragStart(event)" src="https://yt3.ggpht.com/a-/AN66SAyfsmao4f1EEOqkBP2PgpSUcabPJXLZ1sLEnA=s288-mo-c-c0xffffffff-rj-k-no"/>
</div>
<div id="3" ondragover="allowDrop(event)" ondrop="drop(event)" ondragenter="dragEnter(event)" ondragleave="dragLeave(event)" draggable="false">
<img id="c" draggable="true" ondragstart="dragStart(event)" src="https://kinderbilder.download/wp-content/uploads/2018/10/animals-for-dolphin-drawings-pencil-drawings-pinterest-verwandt-mit-delfine-zeichnen-100x100.jpg"/>
</div>
<script>
function allowDrop(ev){
ev.preventDefault();
}
function dragEnter(ev){
var element = document.getElementById(ev.target.id);
element.style.border = "dotted";
element.style.borderColor = "#0b79d0";
}
function dragLeave(ev){
var element = document.getElementById(ev.target.id);
element.style.border = "1px solid #0b79d0";
}
function dragStart(ev){
ev.dataTransfer.setData("src", ev.target.id);
var number = ev.target.id.replace ( /[^\d.]/g, '' );
ev.dataTransfer.setData("text/plain", number);
}
function drop(ev) {
ev.preventDefault();
var src = document.getElementById(ev.dataTransfer.getData("src"));
var srcParent = src.parentNode;
var tgt = ev.currentTarget.firstElementChild;
ev.currentTarget.replaceChild(src, tgt);
srcParent.appendChild(tgt);
var number1 = srcParent.id.replace(/[^\d.]/g, '');
var number2 = ev.currentTarget.id.replace(/[^\d.]/g, '');
var element = document.getElementById(ev.target.id);
element.style.border = "solid 1px #0b79d0";
var number = ev.target.id.replace(/[^\d.]/g, '');
}
</script>
So the dragStart event stores information, such as the image. However, such operation is not possible with touch events.
Now I was wondering, is there a way to do the same thing on mobile, by just imitating the drag events by using the touch events?
from Imitating Drag and Drop Events with Touch Events for Mobile Devices
No comments:
Post a Comment