Created
February 13, 2018 12:40
-
-
Save chrishaensel/e17c9f3838f246d75fe3bd19d6bb92e8 to your computer and use it in GitHub Desktop.
Simple swipe gesture recognizer in vanilla javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
❤️