Keyboard Event Handling: onkeydownQuestion: Which key did the user press?
Answer:
To find out which key the user has pressed,
your script should check the keydown event.keyCode (the key code of the key just pressed)
keydown event.shiftKey (true if the event occured while Shift was pressed)
keydown event.ctrlKey (true if the event occured while Ctrl was pressed)
keydown event.altKey (true if the event occured while Alt was pressed)
(Similarly, to identify the key that the user just released, use the
Click here and press any key This example uses the function fromKeyCode that maps the
function keydownHandler(e) { var evt = e ? e:event; var keyCode = evt.keyCode; var sModifiers = '' +(evt.ctrlKey ? 'Ctrl ' :'') +(evt.shiftKey ? 'Shift ':'') +(evt.altKey ? 'Alt ' :'') ; document.getElementById('sKeyCode').innerHTML = 'keyCode='+keyCode; if (keyCode==16 || keyCode==17 || keyCode==18) document.getElementById('sKeyName').innerHTML= ' key: '+sModifiers; else document.getElementById('sKeyName').innerHTML= ' key: '+sModifiers +fromKeyCode(keyCode); //return true to allow the browser's default response //return false to cancel the default response return true; } //Register the keydown event handler: document.onkeydown=keydownHandler;
Caution: Do not use the
* The See also: |
Copyright © 1999-2012, JavaScripter.net.