Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit the number of times an HTML5 video plays

Tags:

html

loops

video

I know I can loop a video infinitely using the 'loop' attribute. But can I limit the number of times the video loops to perhaps 5 times?

like image 755
Asim K T Avatar asked May 08 '15 06:05

Asim K T


People also ask

How do you stop a video from looping in HTML?

As several comments mentioned, you can remove the loop attribute to get it to stop looping. You could keep it in the HTML code and then just remove it when you want to stop looping.


1 Answers

You will need to use JavaScript to achieve this. Have a look at the snippet below:

var iterations = 1;

document.getElementById('iteration').innerText = iterations;

myVideo.addEventListener('ended', function () {    

    if (iterations < 5) {       

        this.currentTime = 0;
        this.play();
        iterations ++;
        
        document.getElementById('iteration').innerText = iterations;

    }   

}, false);
<div>Iteration: <span id="iteration"></span></div>

<video width="320" height="240" id="myVideo" controls>
    <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4" />
    <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.ogv" type="video/ogg" />
    Your browser does not support the video tag.
</video>

So whats happening here...?

  1. We start by defining a variable called iterations which will store our current iteration. We set this as 1.
  2. We add an event listener to the myVideo video which fires when the video ends.
  3. We then check that the iterations variable hasn't exceeded our number of plays which is 5.
  4. We restart the video by resetting the currentTime to 0 and then using play() function to start the video.
  5. Then we increment the iterations variable by 1 and the whole process starts again until our iterations variable reaches 5 at which point it stops.
like image 195
Chris Spittles Avatar answered Oct 11 '22 19:10

Chris Spittles