Skip to content

Instantly share code, notes, and snippets.

@ethanny2
Created May 27, 2020 00:46
Show Gist options
  • Save ethanny2/44d5ad69970596e96e0b48139b89154b to your computer and use it in GitHub Desktop.
Save ethanny2/44d5ad69970596e96e0b48139b89154b to your computer and use it in GitHub Desktop.
Vanilla JavaScript Double tap event detection on mobile using setTimeout
/* 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());
}
@twilson90
Copy link

The end of a pinch gesture will also trigger this, unless you carefully lift both fingers simultaneously.

@Neophen
Copy link

Neophen commented Nov 8, 2023

why are you using the timeout? it doesn't do anything?

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