0

I wanted to create JS code that outputs video lenght automaticaly when page is loaded. I used body on load function, but it doesnt work. I tried executing the same function using onlick with button and it works. Can someone pelase explain me why "onload" doesnt work / how to solve it, so the user doesnt have to click the button to see the duration of the video and it outputs automaticaly? When I use the button it show the duration corretly, but when using onload function, it only shows "NaN". Thanks for help! Radek

<!DOCTYPE html> 
<html> 
<body onload = "myFunction()"> 

<video width="400" controls id = "video">
  <source src="mov_bbb.mp4" type="video/mp4">
  <source src="mov_bbb.ogg" type="video/ogg">
  Your browser does not support HTML5 video.
</video>

<p>
Video courtesy of 
<a href="https://www.bigbuckbunny.org/" target="_blank">Big Buck Bunny</a>.
</p>
<p id = "demo"></p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
    var x = document.getElementById("video").duration;
    alert(x);
}
</script>
</body> 
</html>
RDK
  • 71
  • 8

1 Answers1

0

Cause that the page loaded doesnt mean that the video loaded. You need to await the videos metadata:

window.onload = _ => {
  const video = document.getElementById("video");
  video.addEventListener('loadeddata', _ => {
     alert(video.duration);
  }, false);
};

More

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151