Events in JavaScript can also be triggered by a key press. These events are particularly helpful when filling a <form> or <form> elements. When a key is pressed, it returns a scan code of the key. These keyboard events are listed below:

The onkeydown event

The onkeydown event occurs when an user press down a key. The scan code is returned for any key pressed.

The onkeypress and textInput events

These events occur when an user is holding a key for prolonged time. The scan code is returned for character keys only. The textInput is introduced and onkeypress is deprecated in DOM level 3, howere it is not widely supported yet.

The onkeyup event

The onkeyup event occurs when an user releases the pressed key.

NOTE: When a character key is pressed from keyboard, the events triggered are onkeydown, onkeypress and onkeyup. For special symbols like ‘shift', ‘backspace’, ‘arrow keys’.. etc, the events triggered may be only onkeydown and onkeyup.

The keyboard events have following properties:

  • keycode - Returns a Unicode character code of the key which triggered the onkeypress event or Unicode key code of key which triggered onkeydown or onkeyup events.
  • charcode - Returns a number, which represents ASCII character of the key which triggered the keypress event.
  • which - Returns a Unicode character code of the key which triggered the onkeypress event or a Unicode key code of key which triggered onkeydown or onkeyup events. This is alternative option for keycode property for cross browser functionality.
  • altkey - Returns true if ALT key is pressed when an event is triggered. This is a read only property.
  • ctrlkey - Returns true if CTRL key is pressed when an event is triggered. This is a read only property.
  • key - Returns the key value of the key which triggered the event. The return value can be string of single character like “a”, “W”, “)” or multiple characters like “F1”, “CAPS LOCK”. It is a DOM Level 3 introduced property and is not yet widely supported.
  • location - Returns the location of the key which triggered the event on a keyboard or a device.
  • metakey - Returns true if the ‘meta’ key in Windows or a ‘cmd’ key in Mac are pressed when the event is triggered. This is a read only property.
  • shiftkey - Returns true if a ‘shift’ key is pressed when the event is triggered. This is a read only property.

The properties keycode and charcode are covered in next chapter in greater details.

Example how to report which keyboard event and property has occured

 

›› go to examples ››