There are many questions and answers on the topic of separating ‘click’ and ‘dblclcik’ events on the same element. They usually use a timer, something like this:
let clicks = 0;
let clickTimer = -1;
function clickMe() {
++clicks;
if (clicks === 1) {
clickTimer = window.setTimeout(function() {
count(false); //perform single-click action
clicks = 0; //after action performed, reset counter
}, 200);
}
else {
clearTimeout(clickTimer); //prevent single-click action
count(true); //perform double-click action
clicks = 0; //after action performed, reset counter
}
}
The trouble is the delay: 200 ms appears to be best from my trials, but then a slow dbl-click sometimes leads to two single clicks. Any bigger timeout leads to a very non-user-friendly delay before a normal click is processed.
Is there a better way?
A JSFiddle to play with, if required.
Using the dblclick
event doesn’t work for me because it emits two click
events first:
let click = document.getElementById("click");
let result = '';
function clickMe() {
result += "single click ";
showResult();
}
function doubleClick() {
result += "double click ";
showResult();
}
function showResult() {
click.innerHTML = result;
setTimeout(()=> {
result = '';
click.innerHTML = result;
},1500)
}
<button onclick="clickMe()" ondblclick="doubleClick()">
Click me
</button>
<p id="click"></p>
2
Answers
Why not using native
dblclick
event (MDN dblclick event)?Full support on most browsers since Dec. 22, 2023.
Please enjoy the new
eventListener
dblclick
.