Last active
August 29, 2015 14:04
-
-
Save MarcoDeJong/359f89675f982628e4a0 to your computer and use it in GitHub Desktop.
Handle left and right swipe only for touchevents
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
<html> | |
<head> | |
<meta name="viewport" content="width=device-width, user-scalable=yes"> | |
</head> | |
<body> | |
<h1>Handle swipeX only. No mouse fallback.</h1> | |
<div id="container" style="background-color:gray;border:1px solid black;width:100%;height:200px;">Swipe here</div> | |
<script> | |
var el = document.getElementById("container"); | |
var xStart=null; | |
el.addEventListener('touchstart', handleTouchStart, false); | |
el.addEventListener('touchmove', handleTouchMove, false); | |
/* Read X coordinate within selected element */ | |
function handleTouchStart(e) { | |
xStart = e.touches[0].clientX; /* for SwipeY read ClientY */ | |
}; | |
function handleTouchMove(e) { | |
/* Only handle moves, if we obtained a X-coordinate before */ | |
if(!xStart) { return; } | |
var xMoved = e.touches[0].clientX; | |
var xDiff = xStart - xMoved; | |
if(xDiff > 0 ) { | |
/* trigger some event or action here for a left swipe */ | |
el.innerHTML='LEFT'; | |
console.log('LEFT'); | |
} | |
else { | |
/* trigger some event or action here for a right swipe */ | |
el.innerHTML='RIGHT'; | |
console.log('RIGHT'); | |
} | |
/* reset position */ | |
xStart=null; | |
}; | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment