I need to customize single click event to double click. And it have to work if second click is clicked in 300 ms.
Asked
Active
Viewed 55 times
1
-
1I think this post can help you! https://stackoverflow.com/questions/5497073/how-to-differentiate-single-click-event-and-double-click-event – Pau Dec 17 '20 at 14:57
-
2Does this answer your question? [How to differentiate single click event and double click event?](https://stackoverflow.com/questions/5497073/how-to-differentiate-single-click-event-and-double-click-event) – Mauricio Arias Olave Dec 17 '20 at 14:59
-
1Here is the guidelines for posting a good question, read it over whenever you have time! https://stackoverflow.com/help/how-to-ask – abc123 Dec 17 '20 at 15:11
2 Answers
0
Something like this should work. Basically you can save the first click, and set a timer to reset that click if no other click is there.
I'm sure there are plenty of better ways to do this, but this works:
let clicked = false;
const timeout = 300;
let timer;
function onClickHandler(e) {
console.log('click');
document.querySelector('#result').innerText = '';
if (timer) window.clearTimeout(timer);
if (!clicked) {
console.log('first time');
clicked = true;
timer = window.setTimeout(() => clicked = false, timeout);
} else {
console.log('double click');
clicked = false;
document.querySelector('#result').innerText = 'Double click!';
}
}
#result{background:red;}
<div onclick="onClickHandler(event)">Click me twice</div>
<div id="result"></div>

casraf
- 21,085
- 9
- 56
- 91
0
Description
Here is an example using the Timeout
built into JavaScript
Example:
// the double click time amount
const doubleClickTimeout = 300
// timer variable used to store our timeout pointer
let timer = undefined
// clear function that kills the timeout/timer and variable
let clear = () => {
if (timer) clearTimeout(timer)
timer = undefined
}
// starts the timeout/timer
let clickStart = () => {
timer = setTimeout(clear, doubleClickTimeout)
}
// gets the area you want to monitor
const doubleClick = document.getElementById("doubleClick")
// set up a onclick event on the doubleClick variable that points to the doubleClick div
doubleClick.onclick = () => {
// if timer isn't undefined then we have a double click
if (timer) {
console.log("double click detected")
// call the clear function: clear the timer
clear()
} else {
// call the clickStart function: start a timer
clickStart()
}
}
<div id="doubleClick">this is a clickable area with custom double clicking</div>

abc123
- 17,855
- 7
- 52
- 82