Last active
November 30, 2018 08:45
-
-
Save edoardocavazza/113b6251d05cdb4fc7e438c8f32d4e9e to your computer and use it in GitHub Desktop.
Move an element using touch events.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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