HTML ondurationchange Event Attribute
Description
The ondurationchange
HTML event attribute is used to specify a JavaScript function to be executed when the duration of a media element changes.
The ondurationchange
event can be used to do things like:
- Update a progress bar to show the new duration of the media element.
- Enable or disable certain controls based on the new duration.
- Display a message to the user informing them of the new duration.
To use the ondurationchange
event, simply add the attribute to the media element you want to listen for the event on. For example, the following code would execute the myFunction()
function when the duration of the video element changes:
<video ondurationchange="myFunction()">
The myFunction()
function could then be used to perform any of the tasks described above.
Here is an example of a myFunction()
function that updates a progress bar to show the new duration of the video element:
function myFunction() {
var video = document.querySelector('video');
var progressBar = document.querySelector('#progress-bar');
// Calculate the percentage of the video that has been played.
var percentagePlayed = video.currentTime / video.duration;
// Set the width of the progress bar to reflect the percentage played.
progressBar.style.width = percentagePlayed * 100 + '%';
}
The ondurationchange
event is a useful way to be notified when the duration of a media element changes. This can be used to implement a variety of features, such as progress bars, dynamic controls, and user feedback.
Syntax
<element ondurationchange="script">
Values
- scriptThe name of the script to use when the event has been triggered.
Example
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<audio id="myAudio" controls ondurationchange="myFunction(this)">
<source src="audio.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<script>
function myFunction(x) {
alert("EXAMPLE: Duration of this audio file: " + x.duration + " seconds");
}
</script>
<p>This example shows how to use the ondurationchange event in an AUDIO element.</p>
<p><strong>Note:</strong>When the audio is downloaded, the “ondurationchange” event will occur, it changes from “NaN” to the actual file duration.</p>
</body>
</html>
Browser Support
The following table will show you the current browser support for the HTML ondurationchange
Event Attribute.
Desktop | |||||
Yes | Yes | Yes | Yes | Yes |
Tablets / Mobile | |||||
Yes | Yes | Yes | Yes | Yes | Yes |
Last updated by CSSPortal on: 14th October 2023