1. Introduction
In this short article, we are going to show how to check if HTML5 video finishes.
2. Solution
Below we presented the solution written in VanillaJS (without external libraries) and with jQuery framework.
2.1. Solution in VanillaJS
VanillaJS comes with addEventListener
method that will fire event listeners on specific event types. We can use it to handle ended
event when the video ends. The snippet code that will achieve that has the following structure.
<video id="sample-video" style="max-width:100%;width:100%;" controls="">
<source src="/storage/snippets/sample-movie.mp4" type="video/mp4">
<source src="/storage/snippets/sample-movie.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>
var v = document.getElementById('sample-video');
v.play();
v.addEventListener('ended', function () {
console.log('ended');
},false);
2.2. Solution using jQuery
In jQuery framework we can use on
method which is used to attach one or more event handlers.
<video id="sample-video" style="max-width:100%;width:100%;" controls="">
<source src="/storage/snippets/sample-movie.mp4" type="video/mp4">
<source src="/storage/snippets/sample-movie.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>
var video = $("#sample-video");
video.get(0).play();
video.on("ended", function() {
console.log('ended');
});
3. Conclusion
In this article, we presented how to check if HTML5 video ended. We used a simple vanilla JavaScript code and script using the jQuery framework. Both methods come down to attaching event listeners (addEventListener
) on a specified video
tag.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}