Last active
December 12, 2022 23:57
-
-
Save renakdup/95e05e8afe853526aae19b3f373f9448 to your computer and use it in GitHub Desktop.
JavaScript
This file contains 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
// 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() | |
} | |
} |
This file contains 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
function isNumeric(n) { | |
return !isNaN(parseFloat(n)) && isFinite(n); | |
} |
This file contains 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 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