You can achieve this by listening for the "ended" event on a particular video and when this occurs call the "play" method on the next video in the queue.
To do this:
- Firstly add an id to each of the videos in the HTML so that you can
then add event listeners to them. (In my code I have added ids
"video1", "video2", "video3".)
- Call a function (e.g playVideo) when a video has "ended", passing in the id of the next video to play.
Note: you only need the autoplay attribute for the first video. From then on we will be calling the play method instead.
JavaScript
window.onload = function(){
//now that the window has loaded we add our event listeners to the videos.
//When video1 has ended, play video2 etc
document.getElementById("video1").addEventListener("ended", function(){ playVideo("video2"); });
document.getElementById("video2").addEventListener("ended", function(){ playVideo("video3"); });
document.getElementById("video3").addEventListener("ended", function(){ playVideo("video1"); });
}
function playVideo(videoID){
//This playVideo function takes in the ID of a video element and plays that video.
var videoElement = document.getElementById(videoID);
videoElement.play();
}
HTML
<video id="video1" class="video" autoplay muted>
<source src="bar.mp4" type="video/mp4">
</video>
<video id="video2" class="video" muted>
<source src="baking.mp4" type="video/mp4">
</video>
<video id="video3" class="video" muted>
<source src="meat.mp4" type="video/mp4">
</video>