How to play multiple video in loop using HTML5 and JavaScript


By the following code we can play multiple video one after anoter by using below script.

Step - 1

Create the index.html file and put video tag code and added first video by default to play.

< video src="v1.mp4" autoplay="true" controls="controls" id="videos" height="200">

Step - 2

add the below code of javscript .

var videoSource = new Array();
videoSource[0] = 'v1.mp4';
videoSource[1] = 'v2.mp4';
let key = 0; // global
const videoCount = videoSource.length;
const element = document.getElementById("videos");
 
function playVideo(videoNum) {
    element.setAttribute("src", videoSource[videoNum]);
    element.setAttribute("type",'video/mp4');
    element.autoplay = true;
    element.load();
    element.play();
}
document.getElementById('videos').addEventListener('ended', myFunctionHandle, false);
 
function myFunctionHandle() {
    key++;
    if (key == videoCount) {
        key = 0;
        playVideo(key);
    } else {
        playVideo(key);
    }
}


Related

String Concatenation in JavaScript
Tag Template literals (Strings) in JavaScript
Destructuring assignment in JavaScript
Difference between null and undefined in JavaScript
localStorage, sessionStorage and cookies in JavaScript?