Sometimes, we want to check if a mouse button is still down after we press it with JavaScript.
In this article, we’ll look at how to check if a mouse button is kept down after we press it with JavaScript.
Listen to the mousedown and mouseup Events
We can listen to the mousedown
and mouseup
events to check if a mouse button is kept down after we press the mouse button.
For instance, we can write:
let mouseDown = 0;
window.onmousedown = () => {
++mouseDown;
if (mouseDown) {
console.log('mouse button down')
}
}
window.onmouseup = () => {
--mouseDown;
if (mouseDown) {
console.log('mouse button down')
}
}
We set the window.onmousedown
and window.onmouseup
properties to functions that change the mouseDown
count to listen for the mousedown
and mouseup
events on the whole tab.
If the mousedown
event is emitted, we increment mouseDown
.
If the mouseup
event is emitted, we decrement mouseDown
.
mousedown
event is emitted when we press the mouse button down.
And mouseup
is emitted when we stop pressing the mouse button.
Therefore, if mouseDown
is bigger than 0, the mouse button is kept down.
Conclusion
We can check if a mouse button is kept down by listening to the mousedown
and mouseup
events and mount how many times the mouse button is pressed down or lifted up.