Can I use javascript to dynamically change a video's source?
How can I change a video's source using JS?
<video id="myVideoTag" width="670" height="377" autoplay="true" controls="controls">
<source src="http://www.test.com/test.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
</video>
Solution 1:
Sure,
-
You can set the
src
attribute on thesource
element:document.querySelector("#myVideoTag > source").src = "http://example.com/new_url.mp4"
Or using jQuery instead of standard DOM methods:
$("#myVideoTag > source").attr("src", "http://example.com/new_url.mp4")
-
Then you need to call the
load
method on the video element:videoElement.load()
Solution 2:
I have faced this problem several times and based on previous experience and digging I can suggest these options:
- replace video tag completely
yes, just re-insert <video>
element with new sources. It's straightforward, but effective approach. Don't forget to re-initialize event listeners.
-
assign video URL to
video.src
this I saw a lot in answers here, on stackoverflow, and also in sources on github.
var video = document.getElementById('#myVideo');
video.src = newSourceURL;
It works, but you cannot provide browser options to choose from.
-
call
.load()
on video element
according to documentation you can update src
attributes for <video>
's <source>
tags and then call .load()
to changes take effect:
<video id="myVideo">
<source src="video.mp4" type="video/mp4" />
<source src="video.ogg" type="video/ogg" />
</video>
<script>
var video = document.getElementById('myVideo');
var sources = video.getElementsByTagName('source');
sources[0].src = anotherMp4URL;
sources[1].src = anotherOggURL;
video.load();
</script>
Nevertheless here it's said that there're problems in some browsers.
I hope it will be useful to have this all in one place.
Solution 3:
I have run into the same problem. According to this thread:
changing source on html5 video tag
it is not possible to change the src of the source tag. you will have to use src of the video tag itself.
Solution 4:
This is working
<video id="videoplayer1" width="240" height="160" controls>
<source id="video_res_1" src="" type="video/ogg">
</video>
and in the javascript
document.getElementById("video_res_1").src = "my video url.ogv";
document.getElementById("videoplayer1").load();
The key is the .load() function that reloads the video player.