faqts : Computers : Programming : Languages : JavaScript : Event handling

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

209 of 262 people (80%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How can I capture key presses?

Apr 21st, 2003 03:39
Shashank Tripathi, Martin Honnen, Nathan Wallace, Martin Honnen


The following will capture key presses inside the document for NN4 and 
all key pressed (inside the document and input fields) for IE4/5 and 
NN6 (as here key events are bubbled up):
document.onkeypress =
  function (evt) {
    var c = document.layers ? evt.which 
            : document.all ? event.keyCode
            : evt.keyCode;
    alert('pressed ' + String.fromCharCode(c) + '(' + c + ')');
    return true;
  };
If you need for NN4 to capture keypresses in text fields/areas too add
if (document.layers)
  document.captureEvents(Event.KEYPRESS);
NOTE: 
If the code can be made to be DOM compliant then it will also work 
with other browsers including Mozilla (+ its variants) and the Operas. 
This is addressed in the following FAQT file: 
http://www.faqts.com/knowledge_base/view.phtml/aid/11802