I wish to have the same button behave different for left click and left mouse down. On click it should add 15 to the current number, on mouse down it adds 1 for as long as the mouse is down
var value = 0;
document.getElementById("Addbtn").addEventListener("mousedown", mouseDown);
document.getElementById("Addbtn").addEventListener("click", mouseClick);
function mouseDown() {
this.value++;
document.getElementById("demo").innerHTML = this.value.tosSring();
}
function mouseClick() {
this.value += 15;
document.getElementById("demo").innerHTML = this.value.tosSring();
}
The problem both events gets fired and I wish to distinguish them so when mouse is hold down click won't fire and vise versa.
Is there a way to achieve this? Cheers
As I said in the comment, since click and mousedown are related and there is no way to disconnect them from each other, the solution can come with a bit of a trick, adding a timeout to determine if it was a "long hold" of the mouse down.
Added a little bonus to disable the click if mouse down has been triggered, you can remove it if not needed.
Also notice, its on a 1 second waiting (1000 ms), change it according to how much you can wait before saying its a mousedown event. 1 second seems long to a user sometime ( about 500 ms is a sweet spot for me)
var value = 0;
var mouseHoldTimeout;
var mouseDownDone = false;
document.getElementById("Addbtn").addEventListener("mousedown", mouseDown);
document.getElementById("Addbtn").addEventListener("click", mouseClick);
function mouseDown() {
mouseHoldTimeout = setTimeout(() => {
value++;
mouseDownDone = true;
document.getElementById("demo").innerHTML = value.toString();
}, 1000);
}
function mouseClick() {
if (mouseHoldTimeout) {
clearTimeout(mouseHoldTimeout);
mouseHoldTimeout = null;
}
if (mouseDownDone) {
mouseDownDone = false;
return;
}
value += 15;
document.getElementById("demo").innerHTML = value.toString();
}
mousedown event will trigger when you click either the left or right or even the middle.It does not matter which one do you click it runs the function. In contrast click event will trigger when you click the left.So it seems when you click the left you trigger mousedown(for left) and click event. As the document provides the click event triggers after mousedown and mouseup.