Cody Raspien
Cody Raspien

Reputation: 1835

Switch video source - same time on slider - JS, HTML5 Video

I have a JS function that changes the video source of an HTML video. A button activates this function. It loads the same new video on switch. There are 2 videos of the same length.

How do I:

  1. interchange the video every time I click the button?

  2. when i click the button, can the video load at the same time the previous video was playing?

HTML:

<button onclick="myFunction()" type="button">Change Video</button><br>

<video id="myVideo" controls autoplay>
    <source id="mp4_src" src="video1.mp4" type="video/mp4">
    <source id="mp4_src" src="video2.mp4">

 </video>

JS

var vid = document.getElementById("myVideo");

function myFunction() { 

    vid.src = "video2.mp4";

vid.load();
} 

Upvotes: 0

Views: 3583

Answers (1)

Gaurang Patel
Gaurang Patel

Reputation: 4530

Here is the fiddle that solves both of your problems, http://jsfiddle.net/egjyd9rs/5/

Basically, the toggle function which takes care of both is as below,

function myFunction() {
    currentlPlayingTime = vid.currentTime;
    if (currentlyPlaying === 1) {
        vid.src = src2;
        currentlyPlaying = 2;
        statusElement.innerText = 'Going to play video2..';
    } else {
        vid.src = src1;
        currentlyPlaying = 1;
        statusElement.innerText = 'Going to play video1..';
    }
    vid.load();
    vid.addEventListener('loadedmetadata', function () {
    vid.currentTime = currentlPlayingTime;
    }, false);
}

Upvotes: 2

Related Questions