Skip to content

Instantly share code, notes, and snippets.

@edoardocavazza
Last active November 30, 2018 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edoardocavazza/113b6251d05cdb4fc7e438c8f32d4e9e to your computer and use it in GitHub Desktop.
Save edoardocavazza/113b6251d05cdb4fc7e438c8f32d4e9e to your computer and use it in GitHub Desktop.
Move an element using touch events.
function draggable(element) {
let currentX = 0;
let currentY = 0;
element.addEventListener('touchstart', (startEvent) => {
const firstTouch = startEvent.touches[0];
let deltaX, deltaY;
const onMove = (moveEvent) => {
// prevent the scrolling
moveEvent.preventDefault();
let moveTouch = moveEvent.touches[0];
// calculate new position
deltaX = moveTouch.clientX - firstTouch.clientX + currentX;
deltaY = moveTouch.clientY - firstTouch.clientY + currentY;
element.style.webkitTransform =
element.style.transform = `translate3d(${deltaX}px, ${deltaY}px, 0)`;
}
const onEnd = () => {
// store the current position
currentX = deltaX;
currentY = deltaY;
// remove all listeners
document.removeEventListener('touchmove', onMove);
document.removeEventListener('touchend', onEnd);
document.removeEventListener('touchcancel', onEnd);
}
document.addEventListener('touchmove', onMove);
document.addEventListener('touchend', onEnd);
document.addEventListener('touchcancel', onEnd);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment