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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With