How to differentiate single click event and double click event?
Instead of utilizing more ad-hoc states and setTimeout, turns out there is a native property called detail
that you can access from the event
object!
element.onclick = event => {
if (event.detail === 1) {
// it was a single click
} else if (event.detail === 2) {
// it was a double click
}
};
Modern browsers and even IE-9 supports it :)
Source: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail
The behavior of the dblclick
event is explained at Quirksmode.
The order of events for a dblclick
is:
- mousedown
- mouseup
- click
- mousedown
- mouseup
- click
- dblclick
The one exception to this rule is (of course) Internet Explorer with their custom order of:
- mousedown
- mouseup
- click
- mouseup
- dblclick
As you can see, listening to both events together on the same element will result in extra calls to your click
handler.