Skip to content

Instantly share code, notes, and snippets.

@joemsak

joemsak/touch.html

Created Dec 22, 2017
Embed
What would you like to do?
<img
class="photo"
alt="wide"
src="https://scontent.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/23347411_108787423227862_4805896712906342400_n.jpg"
/>
<script>
(function () {
Array.prototype.forEach.call(
document.getElementsByClassName("photo"),
function(el) {
el.addEventListener("touchstart", handleStart, false);
el.addEventListener("touchend", handleEnd, false);
el.addEventListener("touchcancel", handleCancel, false);
el.addEventListener("touchmove", handleMove, false);
}
);
var firstTouch,
lastTranslateX = 0;
function handleStart(evt) {
evt.preventDefault();
firstTouch = copyTouch(evt.changedTouches[0]);
}
function handleMove(evt) {
evt.preventDefault();
var touches = evt.changedTouches;
var translateX = lastTranslateX || 0;
for (var i = 0; i < touches.length; i++) {
if (firstTouch.pageX > touches[i].pageX) {
translateX -= firstTouch.pageX - touches[i].pageX;
} else {
translateX += touches[i].pageX - firstTouch.pageX;
}
evt.target.style.webkitTransform = "translateX(" + translateX + "px)";
}
}
function handleEnd(evt) {
evt.preventDefault();
if (evt.target.style.webkitTransform)
lastTranslateX = parseFloat(
evt.target.style.webkitTransform.replace(/[^\d.-]/g, '')
);
}
function handleCancel(evt) {
evt.preventDefault();
}
function copyTouch(touch) {
return { identifier: touch.identifier, pageX: touch.pageX, pageY: touch.pageY };
}
})();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment