VladP VladP - 2 months ago 15
HTML Question

How to change video source with just JavaScript

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

Answer

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.setAttribute('src', srcVideo);
  video.load();
  video.play();
}

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