Yanivn78
Yanivn78

Reputation: 19

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

Upvotes: 1

Views: 1229

Answers (2)

user1129360
user1129360

Reputation: 140

var videoCount = 1;
var videoPlayer = document.getElementById("myvideo");

function runLoop() {
    videoPlayer.src = `app/video${videoCount}.mp4`;
    videoPlayer.play();

    videoCount = (videoCount + 1) % 2;
};

… will solve the problem

You increase the variable before you define the video's file name, so you begin with two... the condition needs to be changed as well, because we wish to set videocount to 1 only after we display the 2nd video

Upvotes: -1

Linus Oleander
Linus Oleander

Reputation: 18127

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);

Upvotes: 3

Related Questions