Search code examples
javascriptdom-eventskeyboard-eventscapslock

How to detect CapsLock and other non-alphanumeric special modifier keys in JavaScript?


Without using the altKey, shiftKey, ctrlKey, is it possible to detect them including CapsLock, Tab and Space ?


Solution

  • Here's an interesting way in which you can find out which key was pressed in JavaScript. This is very helpful

    • To trigger an action based on the key pressed.
    • To prevent Tab playing spoiler by creating indentation rather than switching focus
    • To find out whether Caps Lock is On. The user can be notified especially when filling form fields.
    • Use arrow keys for navigation and so on.

    Here's the JavaScript Code:-

        window.addEventListener("keypress", function(e){
             console.log(e.keyCode);
        });
    
        window.addEventListener("keydown", function(e){
             if(e.keyCode==9)       
             {   
                  console.log("You Pressed Tab");
                  e.preventDefault();
             }
        });
    
        window.addEventListener("keyup", function(e){
            var keyPressed; 
            switch(e.keyCode)
            {
                case 9: return;   // already handled above
                case 18: keyPressed="Alt"; e.preventDefault(); break;
                case 20: keyPressed="Caps Lock"; break;
                case 17: keyPressed="Ctrl"; break;
                case 16: keyPressed="Shift"; break;
                case 37: keyPressed="Left A"; break;
                case 38: keyPressed="Top A"; break;
                case 39: keyPressed="Right A"; break;
                case 40: keyPressed="Bottom A"; break;
                default: keyPressed=e.keyCode;
            }
            console.log("You pressed "+keyPressed);
        });
    

    The reason the switch case construct is not in keydown handler is because personally I don't like multiple execution of the handler when the key is held pressed. Of course more keys can be added into the switch case. Also notice that Tab is under keydown. This is because Tab is triggered when the key is pressed down. Had it been put under keyup, the keypress handler would not have been triggered, changing the window focus, and rendering the keyup handler useless. preventDefault() prevents Tab and Alt from changing the focus.
    The code is just an illustration, change it as necessary.