How to disable full keyboard keys using javascript or jquery?

38,114

Solution 1

try this

document.onkeydown = function (e) {
        return false;
}

for specific area try this

$(".class").keydown(function(event) { 
    return false;
});

Solution 2

While cancelling the keydown effect works for most keys out-of-the-box, some special combos (such as Ctrl+R for reload, Ctrl+T for new tab, etc) can't be blocked in this way and are always sent to the browser instead.

The new (and, at the time of writing, experimental) Keyboard Lock API allows you to capture these kinds of key presses. You can use it like so, or you can also pass in an array of key codes if you only want to lock some of them.

navigator.keyboard.lock();

When you're done, you can call

navigator.keyboard.unlock();

to stop capturing these key codes.

Note that you'll still need to listen for and respond to the keydown event - the new API allows you to capture these lower-level key presses, but you still need to define what will happen when they're pressed.

In your case this would just be cancelling the event (in the style of @Harish Singh's answer), but other use cases would involve performing other actions when certain sets of keys are pressed, prehaps closing the document open in your web app with Ctrl+W rather than the tab, or opening a pause menu when Esc is pressed in a full-screen game, rather than exiting fullscreen.


You can try the Keyboard Lock API today, but browser support is currently limited to Chrome and other Chromium browsers (Edge and Opera) on desktop.


One last note is that for security reasons, the user can always exit the keyboard lock via a browser gesture, to prevent them from getting trapped (which could happen if you used this in conjunction with the Pointer Lock API). In Chrome, this exit gesture is to hold the Esc key for 2 seconds.

Share:
38,114
Mohit Gupta
Author by

Mohit Gupta

Updated on January 07, 2022

Comments

  • Mohit Gupta
    Mohit Gupta over 2 years

    I want to disable full key boards keys using Javascript or jQuery.

    And also, is it possible to disable to keyboard using PHP script?

  • Juned Ansari
    Juned Ansari almost 8 years
    false for windows key
  • Sakkeer A
    Sakkeer A over 5 years
    @Harish Singh and Mohit Gupta Are you sure this will work for all keyboard keys?. Including Alt+f4, Alt+tab,Escape(when window full screen mode activate), and Print Screen button. Please Reply me..