Sometimes, we want to check if mouse button down with JavaScript.
In this article, we’ll look at how to check if mouse button down with JavaScript.
How to check if mouse button down with JavaScript?
To check if mouse button down with JavaScript, we listen for the mousedown and mouseup events.
For instance, we write
let mouseDown = false;
document.body.onmousedown = () => {
mouseDown = true;
};
document.body.onmouseup = () => {
mouseDown = false;
};
if (mouseDown) {
// ....
}
to listen for the mousedown event on the body element with
document.body.onmousedown = () => {
mouseDown = true;
};
We set mouseDown
to true
in document.body.onmousedown
since the mouse button is down.
Likewise, we listen to the mouseup event with
document.body.onmouseup = () => {
mouseDown = false;
};
And we set mouseDown
to false
.
Then we do something is mouseDown
is true
with
if (mouseDown) {
// ....
}
Conclusion
To check if mouse button down with JavaScript, we listen for the mousedown and mouseup events.