Key events

keydown, keypress, and keyup events refer to the user pressing the keys on the keyboard.

Keydownis the initial press
keyupis when the finger is lifted
keypressis somewhere in the middle

The event trigger order of key events is as follows:

  • keydown
  • keypress
  • keyup
// activate autocomplete on keyup
searchField.addEventListener("keyup",, false);

When a key on the keyboard is pressed, your browser fires a "keydown" event. When it is released, a "keyup" event fires.

<p> This page turns violet when you hold the V key . < p>
addEventListener("keydown", function(event) {
    if (event.keyCode == 86) = "violet";

addEventListener("keyup", function(event) {
    if (event.keyCode == 86) = "";

keydown fires not only when the key is physically pushed down. When a key is pressed and held, the event fires again every time the key repeats.

For letter and number keys, the associated key code will be the Unicode character code associated with the (uppercase) letter or number printed on the key. The charCodeAt method on strings gives us a way to find this code.



You can also find out whether these keys are held down by looking at the shiftKey, ctrlKey, altKey, and metaKey properties of keyboard and mouse events.

<p>Press Ctrl-Space to continue.</p>

addEventListener("keydown", function(event) {
    if (event.keyCode == 32 & amp; & amp; event.ctrlKey)

The "keydown" and "keyup" events give you information about the physical key that is being pressed. To get actual text we can get it from another event, "keypress", which fires right after "keydown" (and repeated along with "keydown" when the key is held) but only for keys that produce character input. The charCode property in the event object contains a code that can be interpreted as a Unicode character code. We can use the String.fromCharCode function to turn this code into an actual single-character string.

<p> Focus this page and type something. </p>
addEventListener("keypress", function(event) {
</ script >
The DOM node where a key event originates depends on the element that has focus when the key is pressed. Normal nodes cannot have focus (unless you give them a tabindex attribute), but elements such as links, buttons, and form fields can.
Related Tutorial
Follow Us #