Categories
JavaScript

JavaScript Events Handlers — ondurationchange and onemptied

Spread the love

In JavaScript, events are actions that happen in an app. They are 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 event handlers to respond to these events. Events that happen to DOM elements can be handled by assigning an event handler to properties of the DOM object for the corresponding events. In this article, we will look at the ondurationchange and onemptied event handlers.

ondurationchange

The ondurationchange event handler lets us set our own event handler to handle the durationchange event, which is fired when the duration attribute of the media element like video and audio has been updated. For example, we can use it to get the duration of the video by writing the following HTML code to add a video and a p element for telling us the duration of the video to a web page:

<video width="320" height="240" controls id='video'>  
  <source src="https://sample-videos.com/video123/mp4/240/big_buck_bunny_240p_1mb.mp4" type="video/mp4">  
  Your browser does not support the video tag.  
</video><p id='duration'></p>

Then in our JavaScript code, we can use the ondurationchange property to assign our own event handler to it like in the following code:

const video = document.getElementById('video');  
const duration = document.getElementById('duration');video.ondurationchange = (e) => {  
  console.log(e.srcElement.duration);  
  duration.innerHTML = `The video is ${e.srcElement.duration} seconds long`;  
};

In our event handler function, we have the e parameter, which is an Event object. In it, there’s a srcElement property that has the DOM object representation of the video element, which is the source element triggered the durationchange event to be fired. Since the srcElement is the video element, we can use it to get the duration by using the duration property, which is measured in seconds. Then inside our ondurationchange event handler function, we can display the duration of the video by adding:

duration.innerHTML = `The video is ${e.srcElement.duration} seconds long`;

After that, when we reload the page, we get the video and the ‘ The video is 13.696 seconds long’ displayed since that what we got 13.696 for the duration when we used the e.srcElement.duration to get the duration of the video in seconds. We can also use the addEventListener method to write this instead of like in the following code:

video.addEventListener('durationchange', (e) => {  
  console.log(e.srcElement.duration);  
  duration.innerHTML = `The video is ${e.srcElement.duration} seconds long`;  
})

It’s exactly the same as assigning an event handler to the ondurationchange property.

onemptied

We can set our own event handler for the onemptied property to handle the emptied event, which is fired when the media has become empty. For example, when the media has already been loaded and the load method is called to reload it. To use this property, we can add the following video to our HTML code:

<video width="320" height="240" controls id='video'>  
  <source src="https://sample-videos.com/video123/mp4/240/big_buck_bunny_240p_1mb.mp4" type="video/mp4">  
  Your browser does not support the video tag.  
</video>

Then when we call the load method our video element like in the following code:

const video = document.getElementById('video');  
const duration = document.getElementById('duration');
video.load();
video.onemptied = (e) => {  
  console.dir(e.srcElement);  
};

Then we can see the onemptied event handler being called since we will see the srcElement property being logged in the event handler function. The srcElement has the video element that fired the emptied event. We should get something like the following output from the console.dir call in our event handler function:

accessKey: ""  
assignedSlot: null  
attributeStyleMap: StylePropertyMap {size: 0}  
attributes: NamedNodeMap {0: width, 1: height, 2: controls, 3: id, width: width, height: height, controls: controls, id: id, length: 4}  
autocapitalize: ""  
autoplay: false  
baseURI: "https://fiddle.jshell.net/_display/"  
buffered: TimeRanges {length: 1}  
childElementCount: 1  
childNodes: NodeList(3) [text, source, text]  
children: HTMLCollection [source]  
classList: DOMTokenList [value: ""]  
className: ""  
clientHeight: 240  
clientLeft: 0  
clientTop: 0  
clientWidth: 320  
contentEditable: "inherit"  
controls: true  
controlsList: DOMTokenList \[value: ""\]  
crossOrigin: null  
currentSrc: "[https://sample-videos.com/video123/mp4/240/big\_buck\_bunny\_240p\_1mb.mp4](https://sample-videos.com/video123/mp4/240/big_buck_bunny_240p_1mb.mp4)"  
currentTime: 0  
dataset: DOMStringMap {}  
defaultMuted: false  
defaultPlaybackRate: 1  
dir: ""  
disablePictureInPicture: false  
disableRemotePlayback: false  
draggable: false  
duration: 13.696  
elementTiming: ""  
ended: false  
enterKeyHint: ""  
error: null  
firstChild: text  
firstElementChild: source  
height: 240  
hidden: false  
id: "video"  
innerHTML: "  
  <source src="https://sample-videos.com/video123/mp4/240/big_buck_bunny_240p_1mb.mp4" type="video/mp4">  
  Your browser does not support the video tag.  
"  
...  
offsetHeight: 240  
offsetLeft: 8  
offsetParent: body  
offsetTop: 8  
offsetWidth: 320  
...  
outerHTML: "<video width="320" height="240" controls="" id="video">  
  <source src="https://sample-videos.com/video123/mp4/240/big_buck_bunny_240p_1mb.mp4" type="video/mp4">  
  Your browser does not support the video tag.  
</video>"  
outerText: ""  
ownerDocument: document  
parentElement: body  
parentNode: body  
part: DOMTokenList [value: ""]  
paused: true  
playbackRate: 1  
played: TimeRanges {length: 0}  
playsInline: false  
poster: ""  
prefix: null  
preload: "metadata"  
previousElementSibling: null  
previousSibling: text  
readyState: 4  
remote: RemotePlayback {state: "disconnected", onconnecting: null, onconnect: null, ondisconnect: null}  
scrollHeight: 240  
scrollLeft: 0  
scrollTop: 0  
scrollWidth: 320  
seekable: TimeRanges {length: 1}  
seeking: false  
shadowRoot: null  
sinkId: ""  
slot: ""  
spellcheck: true  
src: ""  
srcObject: null  
style: CSSStyleDeclaration {alignContent: "", alignItems: "", alignSelf: "", alignmentBaseline: "", all: "", …}  
tabIndex: 0  
tagName: "VIDEO"  
textContent: "  
    
  Your browser does not support the video tag.  
"  
textTracks: TextTrackList {length: 0, onchange: null, onaddtrack: null, onremovetrack: null}  
title: ""  
translate: true  
videoHeight: 240  
videoWidth: 320  
volume: 1  
webkitAudioDecodedByteCount: 10995  
webkitDecodedFrameCount: 4  
webkitDisplayingFullscreen: false  
webkitDroppedFrameCount: 0  
webkitSupportsFullscreen: true  
webkitVideoDecodedByteCount: 37638  
width: 320

Alternatively, we can use the addEventListener method to do the same thing:

video.addEventListener('emptied, (e) => {  
  console.dir(e.srcElement);  
});

The video or other media elements like audio have some handy value properties:

  • buffered — a read only property that returns a TimeRanges object, which is an object that has a collection of time ranges for tracking which portion of the media have been buffered when loading it. We can get each range by using the start and end methods by passing an index into either method. It indicates the ranges of the media source that the browser has buffered (if any) at the moment the buffered property is accessed.
  • defaultMuted — a boolean property that reflects the muted HTML attribute, which indicates whether the media element’s audio output should be muted by default.
  • defaultPlaybackRate — a number property indicating the default playback rate for the media. We can set it by assigning a positive number to it or get the value from this property.
  • duration — a read-only double-precision floating-point value indicating the total duration of the media in seconds. If no media data is available, the returned value is NaN. If the media is of indefinite length then like a WebRTC stream, then the value is +Infinity.
  • ended — a read only property that returns a boolean that indicates whether the media element has finished playing.
  • muted — a boolean property that determines whether audio is muted. true if the audio is muted and false otherwise. This is a writable property so we can set it.
  • networkState — a read only property that returns a number that indicates the current state of fetching the media over the network. It can be 0, 1, 2, or 3. 0 means no data, 1 means the element has selected a resource, but it’s not using the network. 2 means the browser is downloading the data, and 3 means no src attribute found.
  • paused — a read only property that returns a boolean that indicates whether the media element is paused.
  • playbackRate — a number that indicates the rate at which the media is being played back. It’s a positive number, and we can set this property as well as get a value from it.
  • played — a read only property that returns a TimeRanges object that contains the ranges of the media source that the browser has played, if there’s any.

Conclusion

The ondurationchange event handler lets us set our own event handler to handle the durationchange event, which is fired when the duration attribute of the media element like video and audio has been updated. We can set our own event handler for the onemptied property to handle the emptied event, which is fired when the media has become empty. For example, when the media has already been loaded and the load method is called to reload it. We can get the element that fired these events with the srcElement property of the e parameter which is an Event object inside our event handler function. It has many useful properties to get us many pieces of information about our media element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *