Keyboard events with Ctrl, Alt, Shift keys

JavaScript FAQ | Keyboard & Mouse Events FAQ  

Question: How do I detect keyboard events with Ctrl, Alt, and Shift keys?

Answer: In modern browsers, your script can check whether a keyboard event occurred while the user was pressing any of the Ctrl, Alt, Shift keys. In the example below, this is accomplished for the keydown events. To implement the Ctrl / Alt / Shift detection, you can use the properties event.ctrlKey, event.altKey, and event.shiftKey. Their values are true if the respective keys are pressed, and false otherwise.

Press any key together with any combination of Ctrl, Alt, and Shift keys, and the key combination will be detected by the following script (that resides in the <HEAD> section of the page). Whenever you press a key on your keyboard, you'll see the event.ctrlKey, event.altKey, event.shiftKey properties on the browser's status bar.

function handleKeyDown(e) {
 var ctrlPressed=0;
 var altPressed=0;
 var shiftPressed=0;

 var evt = (e==null ? event:e);

 altPressed  =evt.altKey;
 ctrlPressed =evt.ctrlKey;
    +  "shiftKey="+shiftPressed 
    +", altKey="  +altPressed 
    +", ctrlKey=" +ctrlPressed 

 if ((shiftPressed || altPressed || ctrlPressed)
     && (evt.keyCode<16 || evt.keyCode>18)) 
   alert ("You pressed the "+fromKeyCode(evt.keyCode)
    +" key (keyCode "+evt.keyCode+")\n"
    +"together with the following keys:\n"
    + (shiftPressed ? "Shift ":"")
    + (altPressed   ? "Alt "  :"")
    + (ctrlPressed  ? "Ctrl " :"")
 return true;

document.onkeydown = handleKeyDown;

Copyright © 1999-2011,