How to Differentiate Single and Double Click Events in JavaScript
I needed a way to detect both single and double clicks on my website.
I used both event listeners below:
document.addEventListener("click", handleClick);
document.addEventListener("dblclick", handleClick);
Unfortunately, the dblclick
event handler wouldn’t prevent the click
event handler from firing, so every double click was preceded by a single click.
In order to fix this, I removed the dblclick
handler completely and began checking for double clicks within the click
handler.
let numClicks = 0;
const handleClick = () => {
numClicks++;
if (numClicks === 1) {
singleClickTimer = setTimeout(() => {
numClicks = 0;
console.log("single click!");
}, 400);
} else if (numClicks === 2) {
clearTimeout(singleClickTimer);
numClicks = 0;
console.log("double click!");
}
};
document.addEventListener("click", handleClick);
numClicks
is a global count variable for the number of clicks that have occurred so far.
The first click will always trigger the timer singleClickTimer
, which runs for 400ms
. If a second click happens within that 400ms
, then a double click will be registered, and the timer (as well as the callback) will be cleared.
The downside to this approach is that it will always take 400ms
to register a single click event.
We can decrease the 400ms
to a smaller number to force single clicks to register faster, but this will also force double clicks to be quicker as well.