Knowledge Base Articles » KB100231: Determining which key was pressed on a keydown event.

If you hit any key on your keyboard and hold it down, you will see the relevant 'keycode' displayed in the textbox above. To achieve this, we first have to trap all 'keydown' events for the document. Netscape Navigator and Internet Explorer require different approaches to this.

For the Netscape code, we can use the captureEvents method of the document object, which instructs the document to capture and handle all events of a particular type, in this case the keydown event. The syntax for this is as follows:


For Internet Explorer, we can simply use the onkeydown event handler for the document object to call our function:

document.onkeydown = getKeycode

Now that we have successfully trapped each keypress, we need to determine which key was pressed and, again, this is handled differently for both main browsers.

For Netscape, we will use the Event object's which property, which returns a number that represents which key was pressed (its ASCII value) at the time the event occurred. Internet Explorer's event object, on the other hand, exposes a keyCode property, so we shall use that. The full source for the getKeycode() function is shown below, along with the necessary browser-detection routine:

<script type="text/javascript">

var blnDOM = false, blnIE4 = false, blnNN4 = false;

if (document.layers) blnNN4 = true;
else if (document.all) blnIE4 = true;
else if (document.getElementById) blnDOM = true;

function getKeycode(e)
  if (blnNN4)
    var NN4key = e.which
    document.frmMain.txtShowKey.value = "Keycode = " + NN4key;
  if (blnDOM)
    var blnkey = e.which
    document.frmMain.txtShowKey.value = "Keycode = " + blnkey;
  if (blnIE4)
    var IE4key = event.keyCode
    document.frmMain.txtShowKey.value = "Keycode = " + IE4key

document.onkeydown = getKeycode
if (blnNN4) document.captureEvents(Event.KEYDOWN)