I think you’ve correctly identified the moment you’d like to intercept the event and precent them. But on recent mobile devices, you’ll need to pass a third parameter into the event listener to say that the event is not passive. Like so:
document.body.addEventListener('touchend', detectDoubleTapClosure(), { passive: false });
More info here: DOM Standard
Update: Mar 28, 2023
Actually, upon further inspecting your gist, you’re not really gaining any advantage from the setTimeout
. I’ve re-written it here:
function createHandler(func, timeout) {
let timer = null;
let pressed = false;
return function() {
if (timer) {
clearTimeout(timer);
}
if (pressed) {
if (func) {
func.apply(this, arguments);
}
clear();
} else {
pressed = true;
setTimeout(clear, timeout || 500);
}
};
function clear() {
timeout = null;
pressed = false;
}
}
// ....
// And you would use it like this:
const ignore = createHandler((e) => e.preventDefault(), 500);
document.body.addEventListener('touchstart', ignore, { passive: false });
For Mobile Safari, the actions go like this:
touchstart
-
touchend
Release quickly -
touchstart
Second one to hold - Magnifying glass comes up
So, if you want to capture the magnifying glass pick up, you need to intercept that second touchstart
— not the end or cancel event.
Good luck!