Question:
I set two event handlers for click
and dblclick
on one element.
For instance,
document.querySelector("div").addEventListener("dblclick", function () { console.log("Bye"); }, false);
document.querySelector("div").addEventListener("click", function () { console.log("Hi"); }, false);
However, when the mouse is double-clicked in IE-11, the click
event is still caught twice.
That is, it turns out
Hi
Hi
Bye
How can I make it so that when the dblclick
event occurs, the click
event is ignored?
Answer:
By simple means, no way.
The problem is that clicks are processed in order. First click
, then dblclick
, and it is necessary that the system somehow predicts whether there will be a second click or not. But she can't.
It seems to me that the only option is
- put a
delay
onclick
processing. This delay will allow the system to "wait" for the second press. If there is no second click, the single click event will pass. - make a
dblclick
processing that would cancel the single click function and run its own
Well, if you organize a JS function for a common click, then you can drive everything into one. Something like this:
var waitingForClick = false;
function theClick(ev) {
switch (ev.detail) {
case 1: // первый клик
waitingForClick = setTimeout(function() {
console.log("Hi");
}, 500);
break;
default: // больше чем один клик
if (waitingForClick) { // отменить ждущий клик
clearTimeout(waitingForClick);
waitingForClick = false;
}
console.log("Bye");
break;
}
}
document.querySelector("div").addEventListener('click', theClick, false);