Skip to content

Instantly share code, notes, and snippets.

@thomhines
Created December 13, 2017 22:14
Show Gist options
  • Save thomhines/048e562490d0f41390895094a5307644 to your computer and use it in GitHub Desktop.
Save thomhines/048e562490d0f41390895094a5307644 to your computer and use it in GitHub Desktop.
Register a swipe gesture on touch screen. Requires jQuery.
var max_swipe_duration = 800;
var min_swipe_distance = 30;
var touchstartX, touchstartY, touchstartTime, touchMove;
// Record initial touch positions
$(window).on('touchstart', function(e) {
touchstartX = e.touches[0].screenX;
touchstartY = e.touches[0].screenY;
touchstartTime = new Date();
});
// touchmove is used because touchend doesn't store X and Y positions
$(window).on('touchmove', function(e) {
touchMove = e;
});
$(window).on('touchend', function(e) {
deltaX = touchMove.touches[0].screenX - touchstartX;
deltaY = touchMove.touches[0].screenY - touchstartY;
var touchDuration = new Date() - touchstartTime;
var swipe_direction;
if(Math.abs(deltaX) < min_swipe_distance) return false;
if(touchDuration > max_swipe_duration) return false;
if(Math.abs(deltaX / deltaY) > 2 && deltaX > 0) swipe_direction = 'right';
if(Math.abs(deltaX / deltaY) > 2 && deltaX < 0) swipe_direction = 'left';
if(Math.abs(deltaY / deltaX) > 2 && deltaY > 0) swipe_direction = 'down';
if(Math.abs(deltaY / deltaX) > 2 && deltaY < 0) swipe_direction = 'up';
if(!swipe_direction) return false;
// Do something based on swipe_direction...
$('.result').html('Swipe direction: ' + swipe_direction);
});
@thomhines
Copy link
Author

Sample at codepen

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment