Dan Dan - 11 days ago 4
Javascript Question

Trying to get full video duration but returning as Nan

I am trying to get the video duration of my player but it returns

NaN
, I am not entirely sure how to access it from here.

<video id="videoPlayerNew" class="video-js vjs-default-skin vjs-controls-enabled" poster="http://camendesign.com/code/video_for_everybody/poster.jpg" data-setup="{}" controls="">
<source src="sample.mp4" type="video/mp4">
<p class="vjs-no-js">Javascript was disabled or not supported</p>
</video>

<script>
var vid = document.getElementById("videoPlayerNew");
console.log(vid.duration);
</script>


The log tells me:
NaN

Answer

Wait for onloadedmetadata event!

var vid = document.getElementById("videoPlayerNew");
vid.onloadedmetadata = function() {
  console.log('metadata loaded!');
  console.log(vid.duration);
};
<video id="videoPlayerNew" class="video-js vjs-default-skin vjs-controls-enabled" poster="http://camendesign.com/code/video_for_everybody/poster.jpg" data-setup="{}" controls="">
  <source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
    <p class="vjs-no-js">Javascript was disabled or not supported</p>
</video>

<script>
</script>

Comments