www.cryer.co.uk
Brian Cryer's Web Resources

How to respond to a key press using JavaScript

This article describes how to catch what keys the user types and how to respond to specific keys.

Page Contents

KeyDown, KeyUp and KeyPress events

If you want to respond to a key press then there are three events that you need to be aware of:

KeyDown
This event is triggered when a key is pressed. It is triggered for all keys, so it will be trigged when the user presses the shift key.
KeyUp
This event is triggered when a key is depressed.
KeyPress
This event is triggered when a key is sent to the browser. The shift, control and alt keys on their own do not generate a KeyPress event.

Lets say that the user types a letter into a text box on a web page, then the order in which events are triggered would be: KeyDown, KeyPress, KeyUp.

How to assign your own event handler for these events

To provide your own event handler for KeyDown, KeyUp or KeyPress use document.onkeydown, document.onkeyup or document.keypress respecitively.

So, by way of example, to assign your own event handler for the KeyPress event use:

document.onkeypress = KeyPressHappened;

This will ensure that the function KeyPressHappened is called each time a key is pressed. The function KeyPressHappened should look something like:

function KeyPressHappened(e)
{
  if (!e) e=window.event;
  .
  .
  .
}

Why the "if (!e) e=window.event;"? Well, unfortunately Internet Explorer and FireFox both implement event handlers slightly differently. Internet Explorer makes the event available via "window.event", but FireFox passes the event in as a parameter. The test is to ensure that beyond that point the same code can (mostly) be used with both Internet Explorer and with FireFox (and Opera too!).

Internet Explorer returns the key-code of the key that has been pressed (or released) via e.keyCode. FireFox uses e.keyCode for both the KeyDown and KeyUp events but e.charCode for the KeyPress event. The following example extends the onkeypress handler above to cater for both IE and FireFox allowing for them returning they key via a different attribute:

function KeyPressHappened(e)
{
  if (!e) e=window.event;
  var code;
  if ((e.charCode) && (e.keyCode==0))
    code = e.charCode
  else
    code = e.keyCode;
  .
  .
  .
}

The key code returned gives the corresponding ASCII character of the key pressed.

If you want to determine whether the shift key, control key or alt key are depressed then the event has corresponding attributes for each of these:

e.shiftKey
True if the shift key is pressed (but does not indicate which shift key where the kwyboard has more than one shift key).
e.ctrlKey
True if the control key is pressed (but does not indicate which control key where the keyboard has more than one control key).
e.altKey
True if the alt key is pressed (but dotes not indicates which alt key where the keyboard has more than one alt key).

A working example

The following example uses document.onkeydown, document.onkeyup and document.onkeypress to show which key is pressed and shows the status of the shift, control and alt keys. If you want to see the JavaScript behind this then look at the source for this page - it is build up using the ideas above.

KeyDown KeyUp KeyPress
     

It is worth noting that some browsers do not generate events for all keys. For example Internet Explorer does not call onkeypress for the arrow keys (although onkeydown and onkeyup are called).

Assigning event handlers to individual components

The above example uses the event handlers for the document. This is fine if you want to catch all keyboard events, but not very useful if you want to be able to deal with keyboard events to different components separately.

Fortunately the same framework applies to individual components. Each component has its own onkeydown, onkeyup and onkeypress event handler.

The following example illustrates this. In this example there is a text field, and it has been assigned all three event handlers. The KeyDown and KeyUp event handlers are used just for information to allow the codes to be displayed.

The KeyPress event handler in this example does a little bit more because it shows how to screen out certain characters - in this example it is used to block any digits from being entered:

KeyDown KeyUp KeyPress
     

Because this example uses an event handler applied to the input field the event handlers only trigger when you type in the field - unlike the previous example which captures all events.

The HTML used for the text field is:

<input name="Text1" onkeydown="return MonitorKeyDown2(event)"
onkeyup="return MonitorKeyUp2(event)"
onkeypress="return MonitorKeyPress2(event)" style="width: 100%" type="text">

and the relevant JavaScript for the KeyPress event handler is:

function MonitorKeyPress2(e)
{
if (!e) e=window.event;
// Block the user of digits.
var code;
if ((e.charCode) && (e.keyCode==0))
code = e.charCode
else
code = e.keyCode; return (code < 48) || (code > 57) }

Practical example: Using arrow keys to move focus

The following is an example of how responding to key presses can allow you to change the default browser behaviour. In this example the arrow keys on the keyboard can be used to move focus between text fields (a bit like how arrow keys can be used to navigate around a spreadsheet):

This example uses some simple JavaScript which is used to respond to the onkeydown event. Whilst it might seem more logical to use the onkeypress event handler, InternetExplorer does not raise this event for the cursor keys (although FireFox does). The JavaScript is:

<script type="text/javascript">
// Copyright (C) 2008 www.cryer.co.uk
// Script is free to use provided this copyright header is included.
function CursorKeyDown(e,topName,leftName,bottomName,rightName)
{
  if (!e) e=window.event;
  var selectName;
  switch(e.keyCode)
  {
  case 37:
    // Key left.
    selectName = leftName;
    break;
  case 38:
    // Key up.
    selectName = topName;
    break;
  case 39:
    // Key right.
    selectName = rightName;
    break;
  case 40:
    // Key down.
    selectName = bottomName;
    break;
  }
  if (!selectName) return;
  var controls = document.getElementsByName(selectName);
  if (!controls) return;
  if (controls.length != 1) return;
  controls[0].focus();
}
</script>

This function takes the event, and the name of the control on the top, left, bottom and right, and sets focus to the appropriate control. The HTML for the example is:

<table border="1" cellpadding="0" cellspacing="0">
<tr>
  <td><input name="r1c1text" type="text" onkeydown="CursorKeyDown(event,undefined,undefined,'r2c1text','r1c2text')"></td>
  <td><input name="r1c2text" type="text" onkeydown="CursorKeyDown(event,undefined,'r1c1text','r2c2text','r1c3text')"></td>
  <td><input name="r1c3text" type="text" onkeydown="CursorKeyDown(event,undefined,'r1c2text','r2c3text',undefined)"></td>
</tr>
<tr>
  <td><input name="r2c1text" type="text" onkeydown="CursorKeyDown(event,'r1c1text',undefined,'r3c1text','r2c2text')"></td>
  <td><input name="r2c2text" type="text" onkeydown="CursorKeyDown(event,'r1c2text','r2c1text','r3c2text','r2c3text')"></td>
  <td><input name="r2c3text" type="text" onkeydown="CursorKeyDown(event,'r1c3text','r2c2text','r3c3text',undefined)"></td>
</tr>
<tr>
  <td><input name="r3c1text" type="text" onkeydown="CursorKeyDown(event,'r2c1text',undefined,undefined,'r3c2text')"></td>
  <td><input name="r3c2text" type="text" onkeydown="CursorKeyDown(event,'r2c2text','r3c1text',undefined,'r3c3text')"></td>
  <td><input name="r3c3text" type="text" onkeydown="CursorKeyDown(event,'r2c3text','r3c2text',undefined,undefined)"></td>
</tr>
</table>

The onkeydown handler for each text input field calls the CursorKeyDown function provided above. Each provides different parameters for CursorKeyDown, supplying the name of the text input field to the top, left, bottom and right - or undefined if there is not one.