HTML onloadedmetadata Event Attribute
Description
The onloadedmetadata
HTML event attribute is used to specify a JavaScript function that will be executed when the metadata for an audio or video element has been loaded. Metadata includes information such as the duration of the media, its dimensions (for video), and any text tracks.
The onloadedmetadata
event is fired after the loadstart
and durationchange
events, and before the loadeddata
and canplay
events. This means that it is a good time to start buffering the media and updating the user interface with information about the media, such as its duration and dimensions.
To use the onloadedmetadata
event attribute, simply add it to the audio or video element that you want to listen for the event on. The value of the attribute should be the name of the JavaScript function that you want to be executed when the event is fired.
For example, the following code will execute the function myFunction()
when the metadata for the video element with the ID myVideo
has been loaded:
<video id="myVideo" onloadedmetadata="myFunction()">
<source src="my-video.mp4" type="video/mp4">
</video>
The myFunction()
function could then be used to update the user interface with information about the video, such as its duration and dimensions.
Here is an example of a complete JavaScript function that could be used to handle the onloadedmetadata
event:
function myFunction(event) {
// Get the video element that fired the event.
const video = event.target;
// Get the duration of the video.
const duration = video.duration;
// Get the dimensions of the video (if it is a video element).
const dimensions = video.videoWidth && video.videoHeight;
// Update the user interface with the video's duration and dimensions.
// ...
}
The onloadedmetadata
event attribute is a useful tool for controlling the playback of audio and video elements. By listening for this event, you can ensure that your web application is ready to play the media before it starts buffering.
Syntax
<element onloadedmetadata="script">
Values
- scriptThe name of the script to use when the event has been triggered.
Example
<!DOCTYPE HTML>
<html>
<body>
<audio id="myAudio" controls onloadedmetadata="myFunction()">
<source src="audio.mp3" type="audio/mpeg">
Your browser does not support the audio tag.
</audio>
<p>Play audio file:</p>
<script>
function myFunction() {
alert("EXAMPLE: Meta data uploaded");
}
</script>
<p>This example shows how to use the onloadedmetadata attribute for an AUDIO element.</p>
</body>
</html>
Browser Support
The following table will show you the current browser support for the HTML onloadedmetadata
Event Attribute.
Desktop | |||||
Yes | Yes | Yes | Yes | Yes |
Tablets / Mobile | |||||
Yes | Yes | Yes | Yes | Yes | Yes |
Last updated by CSSPortal on: 14th October 2023