15

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

Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
PhpDude
  • 1,542
  • 2
  • 18
  • 33
  • Possible duplicate of [Problem retrieving HTML5 video duration](http://stackoverflow.com/questions/2221029/problem-retrieving-html5-video-duration) – roberrrt-s Nov 23 '16 at 11:20

2 Answers2

29

Wait for onloadedmetadata event, The loadedmetadata event is fired when the metadata has been loaded.

var myVideo = document.getElementById("videoPlayerNew");
myVideo.onloadedmetadata = function() {
  console.log('metadata loaded!');
  console.log(this.duration);//this refers to myVideo
};
<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>
Rayon
  • 36,219
  • 4
  • 49
  • 76
3

Try this code below, it adds the event after everything is loaded :

$(document).ready(function(){
  $("#videoPlayerNew").on( "timeupdate", function(event){
      console.log( this.duration);
    });
});
Anand Singh
  • 1,091
  • 13
  • 21
Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67