Introduction
This tip provides a JavaScript example of how to drag, drop, and rotate elements in iPad/Safari. Touch events (ontouchstart
and ontouchmove
) are used to move elements. Gesture events (ongesturestart
and ongesturechange
) are used to rotate elements. To detect that iPad has been rotated, the onorientationchange
event is used.
Using the Code
To use this script, use the MakeiPadDragable
JavaScript function to make some DIV
s dragable. Here is the full JavaScript code:
var startScale = 0;
var startRotation = 0;
function OnLoad(){
if (navigator.platform=="iPad"){
MakeiPadDragable("idBox1");
MakeiPadDragable("idBox2");
MakeiPadDragable("idBox3");
MakeiPadDragable("idBox4");
MakeiPadDragable("idBox5");
}
}
function MakeiPadDragable(id){
var oBox = $(id);
oBox.ontouchstart= function(e){TouchStart(e)};
oBox.ontouchmove=function(e){TouchMove(e)};
oBox.ontouchend=function(e){TouchEnd(e)};
oBox.ontouchcancel=function(e){TouchCancel(e)};
oBox.ongesturestart=function(e){GestureStart(e)};
oBox.ongesturechange=function(e){GestureChange(e)};
oBox.ongestureend=function(e){GestureEnd(e)};
oBox.className = "Dragable";
}
function GetObjPos(obj){
var x = 0;
var y = 0;
var w = obj.offsetWidth;
var h = obj.offsetHeight;
if (obj.offsetParent) {
x = obj.offsetLeft
y = obj.offsetTop
while (obj = obj.offsetParent){
x += obj.offsetLeft;
y += obj.offsetTop;
}
}
return {x:x, y:y, w:w, h:h};
}
function GestureStart(e){
e.target.innerHTML = "GestureStart";
startScale = e.scale;
startRotation = e.rotation;
}
function GestureChange(e){
e.target.innerHTML = "GestureChange, rotation: " + e.rotation + ", scale: " + e.scale;
e.preventDefault();
e.target.style.webkitTransform = 'scale(' + e.scale + startScale + ')
rotate(' + e.rotation + startRotation + 'deg)';
}
function GestureEnd(e){
e.target.innerHTML = "GestureEnd";
}
function TouchStart(e){
e.target.innerHTML = "TouchStart: "
var o = e.target;
var oPos = GetObjPos(o);
o.setAttribute("offsetX", e.targetTouches[0].pageX - oPos.x);
o.setAttribute("offsetY", e.targetTouches[0].pageY - oPos.y);
}
function TouchMove(e){
var o = e.targetTouches[0].target;
e.preventDefault();
var curX = e.targetTouches[0].pageX - parseInt(o.getAttribute("offsetX"));
var curY = e.targetTouches[0].pageY - parseInt(o.getAttribute("offsetY"));;
o.style.position = "absolute";
o.style.top = curY + 'px';
o.style.left = curX + 'px';
}
function TouchEnd(e){
e.target.innerHTML = "TouchEnd: "
}
function TouchCancel(e){
e.target.innerHTML = "TouchCancel: "
}
function UpdateOrientation(){
var s = "";
switch(window.orientation) {
case 0: s = "Portrait"; break;
case -90: s = "Landscape (right, screen turned clockwise)"; break;
case 90: s = "Landscape (left, screen turned counterclockwise)"; break;
case 180: s = "Portrait (upside-down portrait)"; break;
}
$("idBox1").innerHTML = s;
}
function $(s){
return document.getElementById(s);
}
I hope someone might find this example useful.