Sometimes, we want to disable arrow key scrolling in users browser with JavaScript.
In this article, we’ll look at how to disable arrow key scrolling in users browser with JavaScript.
How to disable arrow key scrolling in users browser with JavaScript?
To disable arrow key scrolling in users browser with JavaScript, we disable the default behavior for arrow keys and the space key.
For instance, we write
window.addEventListener(
"keydown",
(e) => {
if (
["Space", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].includes(
e.code
)
) {
e.preventDefault();
}
},
false
);
to call window.addEventListener to listen to the keydown event.
In the keydown event listener, we check if e.code is one of "Space", "ArrowUp", "ArrowDown", "ArrowLeft", or "ArrowRight".
If it is, then we call e.preventDefault to stop the default behavior.
Conclusion
To disable arrow key scrolling in users browser with JavaScript, we disable the default behavior for arrow keys and the space key.