DEV Community

John Au-Yeung
John Au-Yeung

Posted on

JavaScript Events Handlers — Keyboard and Load Events

Subscribe to my email list now at http://jauyeung.net/subscribe/

Follow me on Twitter at https://twitter.com/AuMayeung

Many more articles at https://medium.com/@hohanga

Even more articles at http://thewebdev.info/

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>

Then in the corresponding JavaScript code, we can write the following code to attach the event handler function for the keydown event by setting the onkeydown property of our input element. The event handler function will log the key code of the key that was pressed.

const input = document.querySelector('input');
const log = document.getElementById('log');
input.onkeydown =  e => { 
 log.textContent += ` ${e.code}`;
};

We should get something like:

KeyE KeyR KeyF KeyG KeyT KeyG KeyT KeyG KeyH KeyH KeyF KeyV KeyG KeyB KeyG KeyB

in the element with the ID log .

onkeyup

The onkeyup property of an input element let us attach an event handler function to handle the keyup event. The keyup event is fired when the user releases a key that’s been previously pressed.

The keyup 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 keyup, but the character code 97 will be reported by keypress .

In Firefox, since version 65, the keyup event is also fired during IME composition, to improve cross-browser compatibility for Chinese, Japanese and Korean users. We can ignore the keyup event during IME composition, we can check the isComposing property of the event object that’s provided by the keyup event handler. For example, we can write:

const input = document.querySelector('input');
input.onkeyup =  event => { 
  if (event.isComposing || event.keyCode === 229) {
    return;
  }
};

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>

Then in the corresponding JavaScript code, we can write the following code to attach the event handler function for the keydown event by setting the onkeydown property of our input element. The event handler function will log the key code of the key that was pressed.

const input = document.querySelector('input');
const log = document.getElementById('log');
input.onkeyup =  e => { 
 log.textContent += ` ${e.code}`;
};

We should get something like:

KeyD KeyF KeyG KeyT KeyH KeyG KeyT

onload

The onload property of a DOM element let us set an event handler function to it to handle the load event, which is fired when any element is being loaded. It’s fired at the end of the document loading process. All of the objects in the documents should be in the DOM when the load event is fired, including all images, scripts, links and sub-frames.

There’re also the DOMContentLoaded and DOMFrameContentLoaded , which are fired after the DOM for the page has been loaded but don’t wait for the other resources to finishing loading.

For example, we can use it to run some code after the window or an img element loads by first writing the HTML code:

<!DOCTYPE html>
<html>
  <head>
    <title>Onload</title>
  </head>
  <body>
    <div>Text</div>
    <img
      src="https://images.unsplash.com/photo-1503066211613-c17ebc9daef0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1500&q=80"
    />
    <script src="main.js"></script>
  </body>
</html>

Then we can write the corresponding JavaScript code:

const img = document.querySelector("img");
img.onload = () => {
  console.log("img loaded");
};
window.onload = () => {
  console.log("window loaded");
};

Then we should see:

img loaded  
window loaded

When we load the page.

onloadeddata

The loadeddata event is fired when the first frame of the media has finished loading. It’s applicable to media elements like audio and video . To handle this event, we can set the onloadeddata property of a media element to run an event handler function when this event is fired.

For example, we can also set the onloadeddata property the following code. First, we add the HTML code for the video element:

<video src='https://sample-videos.com/video123/mp4/240/big_buck_bunny_240p_30mb.mp4'></video>

Then in the corresponding JavaScript code, we can set an event handler function with the following code:

const video = document.querySelector('video');
video.onloadeddata = () => {
 console.log('video loaded');
}

The event handler function also has an event object as the first parameter. We can add an event parameter as we do in the following code:

const video = document.querySelector('video');
video.onloadeddata = (event) => {
 console.log(event);
}

Which gets us something like:

bubbles: false
​cancelBubble: false
​cancelable: false
​composed: true
​currentTarget: null
​defaultPrevented: false
​detail: 0
​eventPhase: 0
​explicitOriginalTarget: <html>
​isTrusted: true
​layerX: 0
​layerY: 0
​originalTarget: HTMLDocument https://fiddle.jshell.net/_display/
​rangeOffset: 0
​rangeParent: null
​relatedTarget: null
​returnValue: true
​srcElement: HTMLDocument https://fiddle.jshell.net/_display/
​target: HTMLDocument https://fiddle.jshell.net/_display/
​timeStamp: 1463
​type: "focus"
​view: Window https://fiddle.jshell.net/_display/
​which: 0

The output above is the properties and the corresponding values of the Event object. To see more details about the Event object, we can look at the previous articles.

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. The onkeyup property of an input element let us attach an event handler function to handle the keyup event. The keyup event is fired when the user releases a key that’s been previously pressed. The event object provides the same information as the keydown event handler.

The onload property of a DOM element let us set an event handler function to it to handle the load event, which is fired when any element is being loaded. It’s fired at the end of the document loading process. All of the objects in the documents should be in the DOM when the load event is fired, including all images, scripts, links and sub-frames.

The loadeddata event is fired when the first frame of the media like audio and video has finished loading. To handle this event, we can set the onloadeddata property of a media element to run an event handler function when this event is fired.

Top comments (1)

Collapse
 
shine18 profile image
Aakash Ahmed

Very informative article. This defines it with easy steps on how to bind the event handler to any event in javascript. I found this article too which gives more tips on what javascript events are. 10code.dev/javascript/what-are-jav... Thought I’d leave this here as a helpful source of information