Skip to content

Instantly share code, notes, and snippets.

@chrishaensel
Created February 13, 2018 12:40
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chrishaensel/e17c9f3838f246d75fe3bd19d6bb92e8 to your computer and use it in GitHub Desktop.
Save chrishaensel/e17c9f3838f246d75fe3bd19d6bb92e8 to your computer and use it in GitHub Desktop.
Simple swipe gesture recognizer in vanilla javascript
var swiper = {
touchStartX: 0,
touchEndX: 0,
minSwipePixels: 30,
detectionZone: undefined,
swiperCallback: function() {},
init: function (detectionZone, callback) {
swiper.swiperCallback = callback
detectionZone.addEventListener('touchstart', function (event) {
swiper.touchStartX = event.changedTouches[0].screenX;
}, false);
detectionZone.addEventListener('touchend', function (event) {
swiper.touchEndX = event.changedTouches[0].screenX;
swiper.handleSwipeGesture();
}, false);
},
handleSwipeGesture: function () {
var direction,
moved
if (swiper.touchEndX <= swiper.touchStartX) {
moved = swiper.touchStartX - swiper.touchEndX
direction = "left"
}
if (swiper.touchEndX >= swiper.touchStartX) {
moved = swiper.touchEndX - swiper.touchStartX
direction = "right"
}
if (moved > swiper.minSwipePixels && direction !== "undefined") {
swiper.swipe(direction, moved)
}
},
swipe: function (direction, movedPixels) {
var ret = {}
ret.direction = direction
ret.movedPixels = movedPixels
swiper.swiperCallback(ret)
}
}
//var gestureZone = document.getElementById('container');
var gestureZone = document;
swiper.init(gestureZone, function(e) {
console.log(e)
})
@anki247
Copy link

anki247 commented Feb 19, 2019

❤️

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