Issue
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?
Solution
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...?
- We start by defining a variable called
iterations
which will store our current iteration. We set this as1
. - We add an event listener to the
myVideo
video which fires when the video ends. - We then check that the
iterations
variable hasn't exceeded our number of plays which is5
. - We restart the video by resetting the
currentTime
to0
and then usingplay()
function to start the video. - Then we increment the
iterations
variable by1
and the whole process starts again until ouriterations
variable reaches5
at which point it stops.
Answered By - Chris Spittles
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.