Sometimes, we want to prevent middle mouse click scrolling with JavaScript.
In this article, we’ll look at how to prevent middle mouse click scrolling with JavaScript.
How to prevent middle mouse click scrolling with JavaScript?
To prevent middle mouse click scrolling with JavaScript, we can listen to the mousedown event on the body element.
Then we check if the middle mouse button is clicked and prevent the default scrolling behavior if it is.
For instance, we write:
document.body.onmousedown = (e) => {
if (e.button === 1) {
e.preventDefault();
return false;
}
}
We set document.body.onmousedown
to a function that checks if the middle mouse button is clicked.
We do that checking if e.button
is 1.
If it is, then we call e.preventDefault
and return false
to prevent the default scrolling behavior.
Conclusion
To prevent middle mouse click scrolling with JavaScript, we can listen to the mousedown event on the body element.
Then we check if the middle mouse button is clicked and prevent the default scrolling behavior if it is.