unkind unkind - 11 days ago 4
HTML Question

How do I dynamically change multiple video sources using JavaScript?

I'm trying to dynamically change the video source with the

onclick
event.

Here's the HTML:

<video autoplay loop poster="1.jpg" id="bg">
<source src="/static/media/1.webm" type="video/webm">
<source src="/static/media/1.mp4" type="video/mp4">
</video>


In
onclick
I generate a random link, then I change the source of the
<video>
element:

window.onclick = function() {
var randint = Math.floor(Math.random() * 10) + 1;
var srcmp4 = "http://127.0.0.1:8888/static/media/" + randint.toString() + ".mp4";
document.getElementById('bg').src=srcmp4;
};


If I try to access the source element the same way, by assigning it an id:

<source id="webmid" src="/static/media/1.webm" type="video/webm">


I get null.

I want to dynamically change both .jpg, .webm, .mp4 links. How do I access and assign multiple source elements inside video tag via JS?

Answer

So i did some reading. First i tried deleting children of video, creating new source elements and appending to video, everything worked in page source, but view didn't render any changes. So i followed .canPlayType route to determine if client supports .webm, and if not -- assigning mp4 src directly to video element. Also added small fix so random generated numbers won't repeat. Random video loads when page is loaded and on click events afterwards. Here is the code, it's a mess:

<video autoplay loop poster="" id="bg">
</video>

<script type="text/javascript">
function randlink(a,b){
// generate random int in range of a,b. return str
var c = Math.floor(Math.random()*b)+a;
return "/static/media/"+c.toString();
}

//assign video new random src and poster on page load
window.onload = function(){
var bgvid = document.getElementById('bg');
var randbase = randlink(1,10);
bgvid.poster = randbase + ".jpg";
//check if webm, else mp4 src
if(bgvid.canPlayType('video/webm; codecs="vp8, vorbis"') != ""){
bgvid.src = randbase+".webm";
} else { bgvid.src = randbase+".mp4"}

//change src and poster on click
window.onclick = function() {
var randbase2 = randlink(1,10);
//check if unique
do{
randbase2 = randlink(1,10)
} while (randbase2 == randbase);
randbase = randbase2;
bgvid.poster = randbase2 + ".jpg";
var webmstr = ".webm";
//check if previous was webm, else mp4
if(bgvid.src.indexOf(webmstr) > 0){
bgvid.src = randbase2 +".webm";
}else{
bgvid.src = randbase2 +".mp4";
}}
};
Comments