Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Last active October 20, 2015 18:00
Show Gist options
  • Save tomhodgins/30f5ee50eb403c6f4463 to your computer and use it in GitHub Desktop.
Save tomhodgins/30f5ee50eb403c6f4463 to your computer and use it in GitHub Desktop.
Simple single-digit gesture detection using plain JavaScript. Currently detects a swipe going up, down, left, or right. Touchscreens only! http://staticresource.com/gestures.html
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<meta name=viewport content="width=device-width, initial-scale=1, user-scalable=no">
<title>Swipe Gesture Recognition in JavaScript</title>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0;
font-family: sans-serif;
color: yellow;
background: #013;
position: fixed;
}
h1, div {
text-align: center;
transition: opacity .5s ease-in-out;
}
div {
position: absolute;
width: 50px;
height: 50px;
border-radius: 100%;
background: cornflowerblue;
}
</style>
<head>
<body>
<h1></h1>
<script>
var gesture = {
x: [],
y: [],
match: ''
},
tolerance = 100,
output = document.getElementsByTagName('h1')[0];
window.addEventListener('touchstart',function(e){
e.preventDefault()
for (i=0;i<e.touches.length;i++){
var dot = document.createElement('div');
dot.id = i
dot.style.top = e.touches[i].clientY-25+'px'
dot.style.left = e.touches[i].clientX-25+'px'
document.body.appendChild(dot)
gesture.x.push(e.touches[i].clientX)
gesture.y.push(e.touches[i].clientY)
}
});
window.addEventListener('touchmove',function(e){
for (var i=0; i<e.touches.length; i++) {
var dot = document.getElementById(i);
dot.style.top = e.touches[i].clientY-25+'px'
dot.style.left = e.touches[i].clientX-25+'px'
gesture.x.push(e.touches[i].clientX)
gesture.y.push(e.touches[i].clientY)
}
});
window.addEventListener('touchend',function(e){
var dots = document.querySelectorAll('div'),
xTravel = gesture.x[gesture.x.length-1] - gesture.x[0],
yTravel = gesture.y[gesture.y.length-1] - gesture.y[0];
if (xTravel<tolerance && xTravel>-tolerance && yTravel<-tolerance){
gesture.match = 'Swiped Up'
}
if (xTravel<tolerance && xTravel>-tolerance && yTravel>tolerance){
gesture.match = 'Swiped Down'
}
if (yTravel<tolerance && yTravel>-tolerance && xTravel<-tolerance){
gesture.match = 'Swiped Left'
}
if (yTravel<tolerance && yTravel>-tolerance && xTravel>tolerance){
gesture.match = 'Swiped Right'
}
if (gesture.match!==''){
output.innerHTML = gesture.match
output.style.opacity = 1
}
setTimeout(function(){
output.style.opacity = 0
},500)
gesture.x = []
gesture.y = []
gesture.match = xTravel = yTravel = ''
for (i=0;i<dots.length;i++){
dots[i].id = ''
dots[i].style.opacity = 0
setTimeout(function(){
document.body.removeChild(dots[i])
},1000)
}
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment