How to disable shortcut key in the website using javascript
In this javascript tutorial, we will use vanilla JavaScript to disable shortcut keys on our entire website by binding an event listener to the "keydown" event and preventing the default action of the key press.
in the previous tutorial we have seen, you must read How we can disable the shortcut key in the whole website using jquery.
Here's an example of how we can disable the "Ctrl+S" shortcut key on our entire website:
document.addEventListener("keydown", function(e) {
if(e.ctrlKey && e.which == 83) {
e.preventDefault();
alert("Ctrls + s is disabled") // you can remove this line on the live website
}
});
This code binds an event listener to the "keydown" event on the entire document, and when the event is triggered, it checks if the "Ctrl" key and the "S" key are being pressed. It calls the "preventDefault()" method to prevent the default action of the "Ctrl+S" shortcut key.
We can also use this method to disable other shortcut keys as well, such as "Ctrl+C" (copy) or "Ctrl+V" (paste).
Here is an example for disabling "Ctrl+C" (copy) or "Ctrl+V" (paste).
document.addEventListener("keydown", function(e) {
if(e.ctrlKey && e.which == 67) { //Ctrl+C
e.preventDefault();
alert("Shortcut key Ctrl+C is disabled on this website");
}
if(e.ctrlKey && e.which == 86) { //Ctrl+V
e.preventDefault();
alert("Shortcut key Ctrl+V is disabled on this website");
}
});
If you want to see the all keyboard Key Code Values you must read this article
Here is an example for disabling functions keys like "F5" (refresh) or "F12" (dev tools)
document.addEventListener("keydown", function(e) {
if (e.which === 116) { //F5
e.preventDefault();
alert("F5 key is disabled on this website");
}
if (e.which === 123) { //F12
e.preventDefault();
alert("F12 key is disabled on this website");
}
});