I was asked to assist a developer who is working on a task with hard deadlines, it is a kind mobile game built in HTML5/CSS3 (technically issue is not in HTML). Task is to swap images on touch events, say there 3 images (img1, img2, mg3), user taps and holds on img1 drags it and drops on img3, then img3 should take img1 position on the screen and img1 should take img3. It sounds simple,it is, however it has got it own difficulties too. Just two things to keep in mind 1) Touch events are not exact replacement for mouse events 2) there are no direct solutions always. Below the solution I arrived (it doesn't handle multiple touches).
<!DOCTYPE HTML>
<html>
<meta name="format-detection" content="telephone=no" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, width=device-width" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<head>
</head>
<body>
<div id="div1" style="width:100px;height:100px;background-color:black;color:white;left:10px;position:absolute;"> div1 </div>
<div id="div2" style="width:100px;height:100px;background-color:red;color:white;float:left;left:120px;position:absolute;"> div2 </div>
<div id="div3" style="width:100px;height:100px;background-color:green;color:white;left:230px;position:absolute;"> div3 </div>
<div id="write" style="float:left; width:100%; margin-top:150px;"> </div>
<script type="text/javascript">
var position = ['div1','div2','div3'];
var elemts = document.getElementsByTagName("div");
var pageX ;
var pageY ;
var StyleX;
var StyleY;
var strEle ;
var strPos = 0;
for(var i=0;i<elemts.length;i++)
{
settouchevents(elemts[i]);
}
function settouchevents(div)
{
div.ontouchstart = function (e) {
e.preventDefault();
strEle = div.id;
for(var j=0;j<3;j++)
{
if(position[j] == div.id) strPos = j;
}
}
div.ontouchend = function (e) {
var pos = 0;
var newleft;
if(parseInt(StyleX) < 100) {div.style.left = "10px"; pos=0;}
else if(parseInt(StyleX) < 210) {div.style.left = "120px"; pos=1;}
else if(parseInt(StyleX) > 220) {div.style.left = "230px";pos=2;}
if(pos != strPos)
{
document.getElementById(position[pos]).style.left = (100*strPos + 10*strPos + 10).toString() + "px";
document.getElementById(position[pos]).style.left + "<br>";
position[strPos] = position[pos];
position[pos] = strEle;
}
e.preventDefault();
}
div.ontouchmove = function (e) {
pageX = e.touches[0].pageX;
pageY = e.touches[0].pageY;
StyleX = pageX - div.offsetWidth / 2;
StyleY = pageY - div.offsetHeight / 2;
if (e.touches[0].pageX < 0) {
div.style.left = "10px";
}
else {
div.style.left = StyleX + "px";
}
e.preventDefault();
}
}
</script>
</body>
</html>