Search code examples
javascripthtmlvideo

Looping through videos in HTML5


I have this JS code:

video_count =1;
videoPlayer = document.getElementById("homevideo");

function run(){
    video_count++;
    if (video_count == 4) video_count = 1;
    var nextVideo = "app/video"+video_count+".mp4";
    videoPlayer.src = nextVideo;
    videoPlayer.play();
};

and i have two videos i want to play one after another. The videos are playing fine - first one and after ended the second one but this code loop through the second video instead of playing the first video again and after ended the second video etc.

Can you please help?

Thanks in advance, Yaniv


Solution

  • Use the ended event to trigger the run function again.

    var videoCount = 0;
    var videoPlayer = document.getElementById("myvideo");
    function runLoop() {
      videoPlayer.src = `app/video${videoCount}.mp4`;
      videoPlayer.play();
    
      videoCount = (videoCount + 1) % 4;
    };
    videoPlayer.addEventListener("ended", runLoop);