When using both click
and dblclick
together, the browser will always fire the click event first, because a double–click is essentially two single clicks in quick succession making the click handler run before the dblclick handler.
For handling them differently (and avoid the single–click action overriding the double–click action), distinguish between a single click and a double click. A common way is to use a small timeout
to “wait and see” if a second click happens before running the single–click logic:
const hello = document.getElementById('hello');
let clickTimer = null;
hello.addEventListener('click', function (e) {
// clear any existing timer
clearTimeout(clickTimer);
clickTimer = setTimeout(() =\> {
this.style.background = 'red';
}, 250);
});
hello.addEventListener('dblclick', function (e) {
clearTimeout(clickTimer);
this.style.background = 'yellow';
});
When a dblclick
happens, cancel the pending single–click action so only the double–click logic executes.