Skip to content

Instantly share code, notes, and snippets.

@Mottie
Created October 20, 2011 14:34
Show Gist options
  • Save Mottie/1301303 to your computer and use it in GitHub Desktop.
Save Mottie/1301303 to your computer and use it in GitHub Desktop.
Add Swipe Support
// http://wowmotty.blogspot.com/2011/10/adding-swipe-support.html
// **********
var target = $('#box'),
// allow movement if < 1000 ms (1 sec)
maxTime = 1000,
// swipe movement of 50 pixels triggers the swipe
maxDistance = 50,
// default values
startX = 0,
startTime = 0,
touch = "ontouchend" in document;
target
.bind((touch) ? 'touchstart' : 'mousedown', function(e) {
// prevent image drag (Firefox)
e.preventDefault();
startTime = e.timeStamp;
startX = e.originalEvent.touches ? e.originalEvent.touches[0].pageX : e.pageX;
})
.bind((touch) ? 'touchend' : 'mouseup', function(e) {
startTime = 0;
startX = 0;
})
.bind((touch) ? 'touchmove' : 'mousemove', function(e) {
e.preventDefault();
var currentX = e.originalEvent.touches ? e.originalEvent.touches[0].pageX : e.pageX,
currentDistance = (startX === 0) ? 0 : Math.abs(currentX - startX),
// allow if movement < 1 sec
currentTime = e.timeStamp;
if (startTime !== 0 && currentTime - startTime < maxTime && currentDistance > maxDistance) {
if (currentX < startX) {
// *** swipe left code here ***
}
if (currentX > startX) {
// *** swipe right code here ***
}
startTime = 0;
startX = 0;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment