Its a common question if you gonna make an application that requires to play multiple videos using HTML5 and JavaScript then this is the correct place you are. Here I will explain how you can play multiple videos using HTML5 and JavaScript.
Play Multiple Videos using JavaScript
Step 1
test.html
Copy paste the below code in test.html file-
<video autoplay playsinline loop controls="controls" id="videoPlayer" height="200">
Step 2
script.js
Script file should look like this-
let videoSource = new Array();
videoSource[0] = 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4';
videoSource[1] = 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerEscapes.mp4';
let i = 0; // global
const videoCount = videoSource.length;
const element = document.getElementById("videoPlayer");
function videoPlay(videoNum) {
element.setAttribute("src", videoSource[videoNum]);
element.autoplay = true;
element.load();
}
document.getElementById('videoPlayer').addEventListener('ended', myHandler, false);
videoPlay(0); // load the first video
ensureVideoPlays(); // play the video automatically
function myHandler() {
i++;
if (i == videoCount) {
i = 0;
videoPlay(i);
} else {
videoPlay(i);
}
}
function ensureVideoPlays() {
const video = document.getElementById('videoPlayer');
if(!video) return;
const promise = video.play();
if(promise !== undefined){
promise.then(() => {
// Autoplay started
}).catch(error => {
// Autoplay was prevented.
video.muted = true;
video.play();
});
}
}
Step 3
Save the file and call the script.js file on test.html file. Open the test.html file in browser and you are set!
Here is a code snippet I have prepared on jsFiddle for testing-
Conclusion
This article explains how to play multiple videos one after another using JavaScript and HTML5. If you want to get more JavaScript codes, I would recommend checking them here.
Hi, thank you for your post.
The codes work great, however, in my particular case, the end-user may click on the first video videoSource[0], or one after that, videoSource[1] or videoSource[2]for example. Is there anyway for the array to start playing the next video, regardless of the one selected by the end-user?
Thank you in advance
In that case just pass the clicked index to play in videoPlay(index_here); function. So it will play the selected video and then will automatically play the next one from the list.
Thank you for this post. I am using similar code. How would I add a URL link to each video?
By the word URL link, do you mean there should be a link attached to each video so when user clicks / interacts with the video, that link will open ?
Auto Play not working for the first time of page load, please help
I updated my code to play the 1st video automatically on page load.
How can i repurpose this to preload lets say 3 different videos and put them in different video id elements? so they preload, autoplay on repeat same as here.