Question:
Write custom function to simulate implementation of double click.
Solution:
Use this solution only when you want to bind a single click AND a double click to an element. Otherwise I recommend using the native click
and dblclick
listeners.
These are the differences:
- Vanillajs, No dependencies
- Don't wait on the
setTimeout
to handle the click or doubleclick handler - When double clicking it first fires the click handler, then the doubleclick handler
Click:
- Fires when a mousedown and mouseup event occur on the same element.
- Fires when the user activates the element that has the keyboard focus (usually by pressing Enter or the space bar).
dblclick
- Fires when two mouse click events occur on the same element within a reasonable time. In our solution we have taken 400 ms.
Code:
var singleClick = function () {
console.log('Single');
}
var doubleClick = function () {
console.log('Double');
}
function makeDoubleClick(singleClickCallBack, doubleClickCallBack) {
let clicks = 0, timeout;
return function (){
clicks++;
if (clicks === 1) {
singleClickCallBack.apply(this, arguments);
timeout = setTimeout(() => clicks = 0, 400);
} else {
clearTimeout(timeout);
doubleClickCallBack.apply(this,arguments);
clicks = 0;
}
}
}
document.addEventListener('click', makeDoubleClick(singleClick,doubleClick));
Latest Solution:
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! Modern browsers and even IE-9 supports it :) Source
element.onclick = event => {
if (event.detail === 1) {
// it was a single click
} else if (event.detail === 2) {
// it was a double click
}
};