Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 622
shshaw Avatar asked Jan 22 '14 00:01

shshaw


People also ask

Which HTML attribute starts a video over again every time it is finished?

The loop attribute is a boolean attribute. When present, it specifies that the video will start over again, every time it is finished.

How do you check video is play in Javascript?

log("video is playing"); //DO SOMETHING... } You can use the . paused() method in javascript to check whether a video is playing or not. It will return true if the video is playing and return false if the video is not playing.

How do I know if my video is playing jquery?

click(function() { var video = $("#myvideo"). get(0); video. play(); $(".


1 Answers

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>
like image 176
fregante Avatar answered Sep 24 '22 23:09

fregante