简体   繁体   中英

How can i replicate the 'ended' event on a looped HTML5 video

The 'ended' event does not seem to work for looped videos (attribute loop).

 <video id="video-player" width="946" height="503" preload="auto" loop="loop"  poster="" autoplay="autoplay">
    <source src="video.mp4" type="video/mp4">
 </video>

I would like to trigger an event when the video playback has ended for the first time in the loop.

I worked around this by checking if currentTime == duration on 'timeupdate' :

        var video = $("#video-player");
        video.on('timeupdate', function(e) {
          if (this.currentTime > this.duration - 0.1) {
            ... do things when playback finished for the first time
          }
        })

You can see im checking

duration - 0.1

And this is because the currentTime never seems to reach the full duration value. Right on the end of the playback and the next moment (when it restarts the loop) currentTime is 0 (zero)

Is there a better way? I know i can cause the loop with some extra js and have the 'ended' event available but the loop attribute is required in this case

If your html element has a attribute called loop , you have to remove it. Even if you have written something like <video loop="false"> .

Update

If the loop attribute exists on your element, the ended-event will never be fired!
I would recommend you to loop the video manually and remove the loop attribute.
According to your comment, you need to loop it after the first time. Maybe you can make it like this:

$("#video-player").each(function () {
  this.onended = function (e) {
    //Do whatever you want

    this.play();
  }
}

Two recommondations:

  • Use Vanillebärs idea, but on the first onended -Event add your loop - attribute via js

  • increase your 0.1 value. the currentTime intervall is irregular! It could be, that it is not thrown within your 100ms. check if it works with 1.0 (1sec). But If you wanna make sure the video is really watch to the end, you have to use onended

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM