0👍
This is because you never reset the count
variable of a clicked button when another one is clicked, so the second time you click a button, the count
value will be directly 2.
To fix this I would advise you to use the "click" class as an indicator if the button has been clicked or not. You will then only have to check if the class of the clicked button is present, and if so delete it (and add the class if not)
To check if an element has the class you can use:
const isClicked = element.target.classList.contains("click")
You would need to do this check before removing the "click" class on all the elements
1👍
In general, I would advise against counting clicks to check for double-clicking, as this would also apply to really slow double-clicks or clicks that (such as your example) first clicked element A, then B, then A again.
I’d recommend checking the ‘last clicked’ time, and if that’s greater than, say, 500 ms, do not consider this click a (second, thus) double click.
Here’s an example, using 500ms as a threshold:
myDoubleClickElement.addEventListener('click', (e) => {
if (new Date().getTime() - (e.target._lastTouch || 0) > 500) {
e.target._lastTouch = new Date().getTime();
e.preventDefault(); //does not allow the action to proceed
} else {
//allows the action to proceed
console.log(`Double click on ${e.target}`);
}
});
Here’s a demo
document.getElementById('doubleclick').addEventListener('click', (e) => {
if (new Date().getTime() - (e.target._lastTouch || 0) > 500) {
//not a doubleclick
e.target._lastTouch = new Date().getTime();
e.target.classList.remove("click");
e.preventDefault();
} else {
//a doubleclick
e.target.classList.add("click");
console.log(`Double click on ${e.target}`);
}
});
.click {
background-color: red;
color: white;
}
<button id="doubleclick">Double click me</button>