The ondurationchange event attribute defines a script that will be run when the duration of a media element is updated.
Definition and Usage
➔ This usually happens when the media file is first loaded and its duration value changes from "NaN" (not a number) to the actual length in seconds.
➔ The durationchange event starts at the beginning of a specific sequence.
- loadstart
- durationchange
- loadedmetadata
- loadeddata
- progress
- canplay
- canplaythrough
Syntax
//In HTML
<audio|video ondurationchange="myScript">
//In JavaScript
audio|video_object.ondurationchange=function(){myScript};
//In JavaScript, using EventListener
audio|video_object.addEventListener("durationchange", myScript);
Applies to
This attribute can be used on the following element.
| Attribute | Element |
|---|---|
| ondurationchange | <audio>, <video> |
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML ondurationchange attribute example</title>
<meta charset="utf-8" />
</head>
<body>
<h3>HTML ondurationchange attribute example</h3>
<div class="example">
<video controls id="myvideoid" width="250">
<!-- "https://mdn.github.io/learning-area/html/multimedia-and-embedding/video-and-audio-content/rabbit320.mp4" -->
<source src="source-video-path.mp4"
type="video/mp4">
</video>
</div>
<div>
<button type="button" class="loadButton">Load video</button>
</div>
<div class="event-log">
Event log:<p readonly id="eventLog"></p>
</div>
<script>
let source="";
const video = document.querySelector("video");
const loadButton = document.querySelector(".loadButton");
const eventLog = document.querySelector("#eventLog");
function handleEvent(event) {
eventLog.innerHTML += event.type + "<br>";
}
video.addEventListener("loadeddata", handleEvent);
video.addEventListener("loadedmetadata", handleEvent);
video.addEventListener("durationchange", handleEvent);
video.addEventListener("progress", handleEvent);
video.addEventListener("loadstart", handleEvent);
video.addEventListener("canplay", handleEvent);
video.addEventListener("canplaythrough", handleEvent);
if(video.children[0]==null || video.children[0].getAttribute('src')==null ){
loadButton.addEventListener("click",()=>{
source = document.createElement("source");
//"https://mdn.github.io/learning-area/html/multimedia-and-embedding/video-and-audio-content/rabbit320.mp4"
source.setAttribute("src", "video-source.mp4",);
source.setAttribute("type", "video/mp4");
video.appendChild(source);
});
}
</script>
<p>Note: If you set src correctly, the handler will generate a response.</p>
</body>
</html>
Click on the "copy" button and try this example in your project.