How To Seek an HTML5 Video at A Specific Time On Load

by

Here I am sharing a little tidbit about HTML5 video for anyone that needs a refresher. If one needs to seek a video to a specific time, one can do something like this:

HTML:

<video id="video1" width="320" height="240">
     <source src="movie.mp4" type="video/mp4" />
</video>

Javascript:

document.getElementById("video1").currentTime = 10;

The Javascript statement sets the video1 video’s current time to the 10-second mark. However, this will only work if the browser has already loaded the video’s metadata. The metadata contains pertinent video information such as dimensions and duration. Knowing the video’s duration is required for the browser to seek the video. If it doesn’t have that, then current time will not be set (remains 0). A scenario where this could happen is when a webpage wants to play a video at a specific time when the page loads.

To go about this scenario, the solution would be setting an event handler to listen for the video “loadedmetadata” event.

document.getElementById("video1").addEventListener("loadedmetadata", function() {
     this.currentTime = 10;
}, false);

When the “loadedmetadata” event has fired, then the browser knows that the metadata is loaded. And that point then we can set the current time.

Definitely read up more on the HTML5 video loading process. It is great to know what events fire during a video load.

2 Comments

  1. Pierre on said:

    This is true, the problem I’m running into however, is that the metadata gets loaded AFTER the video itself loads, which in my case happens to be relatively signifcant in size. I only want to buffer(load) the portion of the video needed. (e.g. The currentTime is set to 1000 and I want to play a 30 second clip…start buffering at 1000 seconds) This would require knowing the duration (contained in metadata) in advance.

  2. tiana on said:

    Thanks!! I really needed it !

Leave a Reply

Your email address will not be published. Required fields are marked