Created
May 27, 2020 00:46
-
-
Save ethanny2/44d5ad69970596e96e0b48139b89154b to your computer and use it in GitHub Desktop.
Vanilla JavaScript Double tap event detection on mobile using setTimeout
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
/* Based on this http://jsfiddle.net/brettwp/J4djY/*/ | |
function detectDoubleTapClosure() { | |
let lastTap = 0; | |
let timeout; | |
return function detectDoubleTap(event) { | |
const curTime = new Date().getTime(); | |
const tapLen = curTime - lastTap; | |
if (tapLen < 500 && tapLen > 0) { | |
console.log('Double tapped!'); | |
event.preventDefault(); | |
} else { | |
timeout = setTimeout(() => { | |
clearTimeout(timeout); | |
}, 500); | |
} | |
lastTap = curTime; | |
}; | |
} | |
/* Regex test to determine if user is on mobile */ | |
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { | |
document.body.addEventListener('touchend', detectDoubleTapClosure()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
very good, I modified it a little with 3 additions:
Working here: https://jsfiddle.net/Byte/adLxjmtw/