1

I am building a custom controls HTML5 video player. You can see it HERE. The problem I ran into is being unable to display the video's duration before playing it.

The HTML:

<div class="video-container">
    <video poster="img/flamenco.jpg">
        <source src="flamenco.mp4" type="video/mp4" />
        <source src="flamenco.ogg" type="video/ogg" />
    </video>
    <div class="controls-wrapper">
        <div class="progress-bar">
            <div class="progress"></div>
        </div>
        <ul class="video-controls">
            <li><input type="button" name="play-pause" value="Play" class="play"></li>
            <li><input type="button" name="prev" value="Previous video" class="previous"></li>
            <li><input type="button" name="next" value="Next video" class="next"></li>
            <li class="mute-toggle unmuted"><input type="checkbox" name="mute" value="Mute"></li>
            <li class="volume-container"><input class="volume-slider" type="range" value="1" max="1" step="0.01"></li>
            <li class="show-time disable-select"><span class="current-time">00:00</span><span>/</span><span class="duration"></span></li>
            <li class="fullscreen-container"><input type="button" name="toggle-fullscreen" value="Fullscreen" class="fullscreen"></li>
        </ul>
    </div>
</div>

The JavaScript:

var currentTimeDuration = function(){
    var currTimeStr = Math.round(video.currentTime).toString();
    var durationStr = Math.round(video.duration).toString();
    $('.current-time').text(currTimeStr.timeFormat());
    $('.duration').text(durationStr.timeFormat());
}

$(video).on('timeupdate', function(){
    currentTimeDuration();
});

The problem with the function above is that it only displays the current time and duration of the video after it has started. I wish it would show something like 00:00 / 02:22 on page load.

Any hints? Thank you!

kylegill
  • 314
  • 1
  • 12
Razvan Zamfir
  • 4,209
  • 6
  • 38
  • 252
  • Possible duplicate of [HTML5 Video duration without playing video](http://stackoverflow.com/questions/19592009/html5-video-duration-without-playing-video) – Asons May 02 '17 at 20:53
  • The other question has not bean answered, possibly because it was not clearly formulated. My question is clear and detailed, I believe. – Razvan Zamfir May 02 '17 at 21:02
  • It seems like there might be an issue with this line: "video.onload = currentTimeDuration;" Like maybe currentTimeDuration isn't getting called. Are you able to wrap this in an anonymous function? Maybe something like "video.onload = function() { currentTimeDuration(); }" – sm1215 May 02 '17 at 21:04
  • I checked, that's not the problem. – Razvan Zamfir May 02 '17 at 21:15

1 Answers1

1

video.duration is correct after 'loadedmetadata' event. Try to add metadata loaded handler:

$(video).on('loadedmetadata', function(){
    currentTimeDuration();
});