keydown
, keypress
, and keyup
events refer to the user pressing the keys on the keyboard.
Event | Description |
---|---|
Keydown | is the initial press |
keyup | is when the finger is lifted |
keypress | is somewhere in the middle |
The event trigger order of key events is as follows:
// activate autocomplete on keyup searchField.addEventListener("keyup", addr.search, 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> <script> addEventListener("keydown", function(event) { if (event.keyCode == 86) document.body.style.background = "violet"; }); addEventListener("keyup", function(event) { if (event.keyCode == 86) document.body.style.background = ""; });</script>
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.
console.log("Violet".charCodeAt(0)); //!86 console.log("1".charCodeAt(0)); //!49
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> <script> addEventListener("keydown", function(event) { if (event.keyCode == 32 & amp; & amp; event.ctrlKey) console.log("Continuing!"); }); </script>
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> <script> addEventListener("keypress", function(event) { console.log(String.fromCharCode(event.charCode)); }); </ script >