0

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();
} 
Cody Raspien
  • 1,753
  • 5
  • 26
  • 51
  • Use this post for setting the previous video time: http://stackoverflow.com/questions/5981427/start-html5-video-at-a-particular-position-when-loading. Save your sources in an array and then count up an index each time you click. – Philipp Oct 14 '14 at 12:08
  • got the time working -http://pastebin.com/gx5dYH3H but now need to make it so that the video source switches to and fro. – Cody Raspien Oct 14 '14 at 13:36

1 Answers1

2

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);
}
Gaurang Patel
  • 4,310
  • 6
  • 27
  • 32