3

Here is my simple page (css not added):

<a onclick="PlayVideo('http://www.myhost.com/..../myVideo1.mp4');">Play Video 1</a>
<a onclick="PlayVideo('http://www.myhost.com/..../myVideo2.mp4');">Play Video 2</a>

<div id="xxxxxx">
    <div><a onclick="StopVideo();">X</a>
         <video id="video" width="520" height="360" controls></video>
    </div>
</div>


<script>
    function PlayVideo(srcVideo) {
        var video = document.getElementById('video');
        var source = document.createElement('source');   
        source.setAttribute('src', srcVideo);
        video.appendChild(source);
        video.play();
    }

    function StopVideo() {
        document.getElementById('video').pause();
    }
</script>

When I click "Play Video 2" it's still playing video 1. So how do I switch the video source to play in same video element? I need just pure JavaScript if that's possible

1
  • You're adding more sources to the existing video element. You need to clear out the previously loaded sources, or better yet, create a new video element each time. Commented Sep 26, 2016 at 17:19

1 Answer 1

8

You do not need to append new source. Just set new src attribute and call video.load function.

See working JSFiddle

video = document.getElementById('video');
source = document.getElementById('source');

function PlayVideo(srcVideo){
  video.pause();
  source.src = srcVideo;
  video.load();
  video.play();
}

function StopVideo(){
  document.getElementById('video').pause();
}

EDIT: Changed .setAttribute('src',srcVideo) to .src = srcVideo because this is commonly used method to change source.

Sign up to request clarification or add additional context in comments.

6 Comments

good example but it just doesn't work with files/url like myhost.com/..../myVideo2.mp4
@VladP. Then it must be some problem with your host. I also tested it on my localhost (built using WAMP, XAMPP and Node.js) and it works properly.
it works/plays in my example in the question. I just cannot change the source. So it's not host problem
@VladP. Can you successfully change source in my fiddle? If yes, then copy-paste it and it sould work.
Oh. sorry for the confusion.. It does work.. Thank you very much.. I mark it as answered
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.