Executing function at end of html5 video

willdanceforfun picture willdanceforfun · Jan 25, 2013 · Viewed 74.6k times · Source

I have a html video, and I am wanting to run a function when a video ends. I have tried the following but I get nothing:

$(document).ready(function(){

    $('video').live('ended',function(){

        alert('video ended');

    });

});

Any ideas why this isn't triggering at the end of a video? Or have I not provided enough information to answer anything here?

Note: I'm using live() function and not on() because of the need for jQuery 1.7 with this project.

Answer

fboes picture fboes · Jul 10, 2014

For your paste & copy pleasure the jQuery solution:

<video width="320" height="240">
  <source src="movie.mp4" type="video/mp4">
</video>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>/*<![CDATA[*/
  $(document).ready(function(){
    $('video').on('ended',function(){
      console.log('Video has ended!');
    });
  });
/*]]>*/</script>

Replace the 'video'-part with the correct selector for your video.

EDIT: Here is the solution without jQuery:

<video width="320" height="240">
  <source src="movie.mp4" type="video/mp4">
</video>
<script>/*<![CDATA[*/
  document.querySelector('video').addEventListener('ended',function(){
    console.log('Video has ended!');
  }, false);
/*]]>*/</script>

Replace the 'video'-part with the correct selector for your video.