I am trying to translate Touch events to Mouse events for my "desktop drag and drop" code. I used translation function that mentioned in this question Javascript Drag and drop for touch devices . But the final code of mine does not work in touch mode. Can any body help me solve this? I use CTRL+SHIFT+M to change desktop mode to touch mode in my browser. Below is my code. BTW this works perfect in mouse desktop mode.
<html>
<body>
<style>
#wrapper {
width: 400px;
height: 400px;
background-color: #fbfcfc;
position: relative;
}
#mydiv {
cursor: move;
position: absolute;
z-index: 9;
display: inline-block;
text-align: center;
border: 1px solid #d3d3d3;
}
</style>
<div id="wrapper" style="width:400px; height:400px; border: 0.1vw solid gray;">
<div id="mydiv" style="width:40px; height:40px; background-color:red">
</div>
</div>
<script>
// Translate Touch to Mouse events
function touchHandler(event) {
var touch = event.changedTouches[0];
var simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent({
touchstart: "mousedown",
touchmove: "mousemove",
touchend: "mouseup"
}[event.type], true, true, window, 1,
touch.screenX, touch.screenY,
touch.clientX, touch.clientY, false,
false, false, false, 0, null);
touch.target.dispatchEvent(simulatedEvent);
event.preventDefault();
}
function init() {
document.addEventListener("touchstart", touchHandler, true);
document.addEventListener("touchmove", touchHandler, true);
document.addEventListener("touchend", touchHandler, true);
document.addEventListener("touchcancel", touchHandler, true);
}
// Translate Touch to Mouse event
//Make the DIV element draggagle:
dragElement(document.getElementById("mydiv"));
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
/* if present, the header is where you move the DIV from:*/
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
} else {
/* otherwise, move the DIV from anywhere inside the DIV:*/
elmnt.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
function closeDragElement() {
/* stop moving when mouse button is released:*/
document.onmouseup = null;
document.onmousemove = null;
}
}
</script>
</body>
</html>