shshaw shshaw - 4 months ago 25
Javascript Question

Detect in Javascript when HTML5 <video> loop restarts?

I have a looping HTML5 video using

<video loop="true">
, and I want to know when the video loops. The event listener
play
only fires when the video is started initially, and
ended
never fires.

The imprecise nature of
timeupdate
makes me nervous using
if ( v.currentTime <= 0 )
, but it does seem to work. Is there a better way to detect when the video restarts?

Here's my basic setup:

<video autoplay="true" loop="true" muted="true">
<source src="vidoe.mp4" type="video/mp4">
<source src="video.webm" type="video/webm">
<source src="video.ogv" type="video/ogg">
</video>
<div id="Video-Time"></div>

<script>
var v = document.getElementsByTagName('video')[0]
var t = document.getElementById('Video-Time');

v.addEventListener('timeupdate',function(event){
t.innerHTML = v.currentTime;
if ( v.currentTime <= 0 ) { console.log("Beginning!"); } // It does trigger when looping, surprisingly
},false);
v.addEventListener('play', function () {
console.log("play!"); // Only triggered when the video initially starts playing, not when the loop restarts
},false);
v.addEventListener('ended', function () {
console.log("ended!"); // Never triggered
},false);
</script>

Answer

I think the most reliable way is to loop it yourself. Remove the loop attribute and do this:

document.querySelector('video').addEventListener('ended', function () {
  console.count('loop restart');
  this.play();
})
<video autoplay muted src="https://rawgit.com/bower-media-samples/big-buck-bunny-480p-5s/master/video.mp4"></video>

Comments