JavaScript Events Handlers — Keyboard and Load Events
In JavaScript, events are actions that happen in an app. They’re triggered by various things like inputs being entered, forms being submitted, and changes in an element like resizing, or errors that happen when an app is running, etc. We can assign an event handler to respond to these events.
Events that happen to DOM elements can be handled by assigning a handler to properties of the DOM object for the corresponding events. In this article, we’ll look at how to use the onkeydown
and onkeypress
properties of an editable input element, and the onload
property for any DOM element. We will also look at the onloadeddata
property for media elements like audio
and video
.
onkeydown
We can set an event handler function to the onkeydown
property of an input DOM element to handle the keydown
event. The keydown
event is fired when any key is pressed down regardless of whether they produce a character value. The keydown
event provides a code indicating which key is pressed, while the keypress
event provides the character which is entered. For example, lowercase ‘a’ will be reported as keycode 65 with keydown
, but the character code 97 will be reported by keypress
. keypress
is deprecated, so it shouldn’t be used in production code.
In Firefox, since version 65, the keydown
event is also fired during IME composition, to improve cross-browser compatibility for Chinese, Japanese and Korean users. We can ignore the keydown
event during IME composition, we can check the isComposing
property of the event
object that’s provided by the keydown
event handler. For example, we can write:
const input = document.querySelector('input');input.onkeydown = event => {
if (event.isComposing || event.keyCode === 229) {
return;
}
};
Whenever, we type in Chinese, Japanese or Korean, the isComposing
property will have the value true
and the keyCode
property will have the value 229.
We can also use it to log the value of the key code that’s pressed by the user on the keyboard. We can first put the following HTML code:
<input type="text" id="input" required>
<p id="log"></p>