Skip to content

Instantly share code, notes, and snippets.

@pgaskin
Last active March 6, 2018 16:11
Show Gist options
  • Save pgaskin/3b2d6e22d817ed46cfdc038edc1edaa3 to your computer and use it in GitHub Desktop.
Save pgaskin/3b2d6e22d817ed46cfdc038edc1edaa3 to your computer and use it in GitHub Desktop.
A simple way to detect swipes in JS.
function Swiper(el, left, right, up, down) {
var xD = null,
yD = null;
el.addEventListener("touchstart", function(ev) {
xD = ev.touches[0].clientX;
yD = ev.touches[0].clientY;
}, false);
el.addEventListener("touchmove", function(ev) {
if (!xD || !yD) return;
var xU = ev.touches[0].clientX,
yU = ev.touches[0].clientY,
dX = xD - xU,
dY = yD - yU,
horizontal = Math.abs(dX) > Math.abs(dY);
if ((horizontal && Math.abs(dX) < 30) || (!horizontal && Math.abs(dY) < 30)) return;
horizontal
? dX > 0 ? left() : right()
: dY > 0 ? up() : down();
xD = yD = null;
}, false);
}
function Swiper(f,g,h,k,l){var b=null,c=null;f.addEventListener("touchstart",function(a){b=a.touches[0].clientX;c=a.touches[0].clientY},!1);f.addEventListener("touchmove",function(a){if(b&&c){var d=b-a.touches[0].clientX;a=c-a.touches[0].clientY;var e=Math.abs(d)>Math.abs(a);e&&30>Math.abs(d)||!e&&30>Math.abs(a)||(e?0<d?g():h():0<a?k():l(),b=c=null)}},!1)};
Swiper(
document,
console.log.bind(console, "left"),
console.log.bind(console, "right"),
console.log.bind(console, "up"),
console.log.bind(console, "down")
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment