How To Seek an HTML5 Video at A Specific Time On Load
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