I am currently attempting to implement a feature where I can drag a div (#drag
) within its parent container (#container
) using only pure JavaScript. This functionality is specifically required to work on iPad devices only.
After writing a script that functions perfectly when testing in Chrome with touch events emulation turned on, I encountered an issue on an actual iPad. When dragging the div too quickly, it no longer follows my finger.
My initial thought was that my finger might be moving out of the element too fast, so I tried setting the addEventListener
on the body instead of the div, but unfortunately, the problem persisted.
If anyone has any insights into why this issue is occurring and how it can be resolved to ensure smooth functionality on iPads, I would greatly appreciate your input.
Demo: http://jsfiddle.net/kxrEZ/
Javascript:
var dom = {
container: document.getElementById("container"),
drag: document.getElementById("drag"),
}
var container = {
x: dom.container.getBoundingClientRect().left,
y: dom.container.getBoundingClientRect().top,
w: dom.container.getBoundingClientRect().width,
h: dom.container.getBoundingClientRect().height
}
var drag = {
w: dom.drag.offsetWidth,
h: dom.drag.offsetHeight
}
target = null;
document.body.addEventListener('touchstart', handleTouchStart, false);
document.body.addEventListener('touchmove', handleTouchMove, false);
document.body.addEventListener('touchend', handleTouchEnd, false);
function handleTouchStart(e) {
if (e.touches.length == 1) {
var touch = e.touches[0];
target = touch.target;
}
}
function handleTouchMove(e) {
if (e.touches.length == 1) {
if(target === dom.drag) {
moveDrag(e);
}
}
}
function handleTouchEnd(e) {
if (e.touches.length == 0) { // User just took last finger off screen
target = null;
}
}
function moveDrag(e) {
var touch = e.touches[0];
var posX = touch.pageX - container.x - drag.w / 2;
var minX = 0;
var maxX = container.w - drag.w;
if(posX < minX) {posX = minX;}
else if(posX > maxX) {posX = maxX;}
var posY = touch.pageY - container.y - drag.h / 2;
var minY = 0;
var maxY = container.h - drag.h;
if(posY < minY) {posY = minY;}
else if(posY > maxY) {posY = maxY;}
dom.drag.style.left = posX + "px";
dom.drag.style.top = posY + "px";
}