Skip to content

Instantly share code, notes, and snippets.

@WillsonSmith
Created July 3, 2012 17:19
Show Gist options
  • Save WillsonSmith/3041151 to your computer and use it in GitHub Desktop.
Save WillsonSmith/3041151 to your computer and use it in GitHub Desktop.
Swipe Events (on end touch)
(function(){ //Self executing, anonymous function
//Leave out above if including in already existing script
function Swipe(){
var firstX, lastX;
function swipeRight(){
//Do stuff on swipe right
console.log('right');
}
function swipeLeft(){
//Do stuff on swipe left
console.log('left');
}
document.addEventListener('touchstart', function(e){
var touch = e.touches[0];
firstX = touch.pageX;
});
document.addEventListener('touchmove', function(e){
e.preventDefault();
var touch = e.touches[0];
lastX = touch.pageX;
//add sliding & transitions here if required
});
document.addEventListener('touchend', function(){
if (firstX < lastX - 50){
swipeRight();
}else if (firstX > lastX + 50){
swipeLeft();
}
});
}
//call swipe some time after here
//Swipe();
//Leave out below if including in already existing script
})();//() causes self execution.
//1k - minified: 360b
function Swipe(){function n(){console.log("right")}function r(){console.log("left")}var e,t;document.addEventListener("touchstart",function(t){var n=t.touches[0];e=n.pageX});document.addEventListener("touchmove",function(e){e.preventDefault();var n=e.touches[0];t=n.pageX});document.addEventListener("touchend",function(){e<t-50?n():e>t+50&&r()})};
//I recommend minifying this yourself
//use this one if including in an already existing script
(function(){function e(){function n(){console.log("right")}function r(){console.log("left")}var e,t;document.addEventListener("touchstart",function(t){var n=t.touches[0];e=n.pageX});document.addEventListener("touchmove",function(e){e.preventDefault();var n=e.touches[0];t=n.pageX});document.addEventListener("touchend",function(){e<t-50?n():e>t+50&&r()})}})();
//I recommend minifying this yourself
//use this if including as <script src="Swipe.min.js"> tag
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment