Skip to content

Instantly share code, notes, and snippets.

@renakdup
Last active December 12, 2022 23:57
Show Gist options
  • Save renakdup/95e05e8afe853526aae19b3f373f9448 to your computer and use it in GitHub Desktop.
Save renakdup/95e05e8afe853526aae19b3f373f9448 to your computer and use it in GitHub Desktop.
JavaScript
// Detect swipe event. Detect touch swipe event.
// Example
detectSwipeEvent(document.getElementsByClassName('js-mobile-nav__background')[0], function (orientation) {
console.log(orientation)
});
/**
* @param element js element
* @param callback Your callback invoke on swipe event. Attribute "swipe orientation" transfer to callback.
*/
function detectSwipeEvent (element, callback) {
element.addEventListener('touchstart', startTouch, false)
element.addEventListener('touchmove', moveTouch, false)
// Swipe Up / Down / Left / Right
var initialX = null
var initialY = null
function startTouch (e) {
initialX = e.touches[ 0 ].clientX
initialY = e.touches[ 0 ].clientY
}
function moveTouch (e) {
if (initialX === null) {
return
}
if (initialY === null) {
return
}
var currentX = e.touches[ 0 ].clientX
var currentY = e.touches[ 0 ].clientY
var diffX = initialX - currentX
var diffY = initialY - currentY
if (Math.abs(diffX) > Math.abs(diffY)) {
// sliding horizontally
if (diffX > 0) {
callback('left')
} else {
callback('right')
}
} else {
// sliding vertically
if (diffY > 0) {
callback('up')
} else {
callback('down')
}
}
initialX = null
initialY = null
e.preventDefault()
}
}
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var rand = min + Math.floor(Math.random() * (max + 1 - min));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment