shshaw shshaw - 1 year ago 125
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
only fires when the video is started initially, and
never fires.

The imprecise nature of
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">
<div id="Video-Time"></div>

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

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

Answer Source

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');;
<video autoplay muted src=""></video>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download