user2454060 user2454060 - 1 month ago 8
Javascript Question

When I autoplay an HTML5 video, I can't loop it from a specific point

I have a video that I want to autoplay when the page is loaded, and loop from a specific point (16 seconds) when it ends. If I add "autoplay" in the HTML the video doesn't loop at all. If I add "loop" in the HTML the video loops but disregards the EventListener. If I don't add loop or autoplay and play the video manually it loops at 16 seconds like I want it to.

How can I have my video autoplay on page load and also loop at 16 seconds? Below is the code I have:



document.getElementById('video1').addEventListener('ended', function(){
this.currentTime = 16;
this.play();
}, false);

<video id="video1" width="100%" autoplay >
<source src="video1.webm" type="video/webm">
</video>




Answer Source

I managed to reproduce the problem you experienced when I had the code in the head tag rather than at the bottom. My test which worked looked like this:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>html video</title>
  </head>

  <body>
    <div >
        <video id="video1" width="100%" autoplay controls>
            <source src="test2.webm" type="video/webm">           
        </video>
    </div>
  </body>
  <script>
        document.getElementById('video1').addEventListener('ended', function(){
                this.currentTime = 16; 
                this.play();
        }, false);
    </script>
</html>