Start HTML5 video at a particular position when loading?

Johnydep picture Johnydep · May 12, 2011 · Viewed 170.6k times · Source

I need HTML5 video to start at certain point. Let's say at time 50 seconds onward.

I tried but its not working as expected. is there something i am doing wrong?

Here is the code:

   <video id="vid1" width="640" height="360">
       <source src="file.webm" type="video/webm" /> 
       Your browser does not support the video tag.
   </video>
   <script>
       document.getElementById('vid1').currentTime = 50;
   </script> 

When the page loads, it just starts playing from beginning. However if I call this during playback like after some time, it works fine. Is there anything I am missing?

Answer

Richard M picture Richard M · May 12, 2011

You have to wait until the browser knows the duration of the video before you can seek to a particular time. So, I think you want to wait for the 'loadedmetadata' event something like this:

document.getElementById('vid1').addEventListener('loadedmetadata', function() {
  this.currentTime = 50;
}, false);