zac
zac

Reputation: 45

how would i add more video sources to my javascript code?

i have 5 different videos and i want them to add more then one source to them so that they can play in more browsers but im not sure on how to make it so you can do that. here is what my javascript looks like it is pretty repetitive

function addVideo1() {
  var changeStuff = document.getElementById("myVideo");
    changeStuff.src = "video/demoreel.mp4";

}

function addVideo2() {
 var changeStuff = document.getElementById("myVideo");
    changeStuff.src = "video/video1.mp4";
}

function addVideo3() {
    var changeStuff = document.getElementById("myVideo");
    changeStuff.src = "video/video2.mp4";
}

function addVideo4() {
    var changeStuff = document.getElementById("myVideo");
    changeStuff.src = "video/video3.mp4";

}

function addVideo5() {
    var changeStuff = document.getElementById("myVideo");
    changeStuff.src = "video/video4.mp4";
}

Upvotes: 0

Views: 308

Answers (3)

Tim Hobbs
Tim Hobbs

Reputation: 2017

Try this jsFiddle, it should do what you want.

ARGH! I did it in jQuery, sorry. I wasn't paying attention. Ok, I went back and did it in plain ol' javascript.

HTML

<div id="video"><video></video></div>
<ul>
    <li><a href="#" data-video="video1.mp4">Video 1</a></li>
    <li><a href="#" data-video="video2.mp4">Video 2</a></li>
    <li><a href="#" data-video="video3.mp4">Video 3</a></li>
</ul>

JS

var elems = document.getElementsByTagName("a");
for (i = 0; i < elems.length; i ++) {
    elems[i].addEventListener("click", function () {
        var video = this.dataset["video"];
        var source = document.createElement("source");
        source.src = video;
        var container = document.getElementById("video");
        var v = container.firstChild;
        v.innerHTML = "";
        v.appendChild(source);
    });
}

CSS

Not necessary, just to "prettify" it a bit

html { padding: 10px; }
#container { width: 450px; }
#video { width: 320px; height: 240px; border: 3px solid #CCC; }
ul { margin: 10px 0; width: 320px; padding: 0; }
ul li { display: inline; margin: 0 10px 0 0; padding: 0;  }

Upvotes: 1

FrancescoMM
FrancescoMM

Reputation: 2960

You can try something like this (untested, typed on mobile).

function addSource(id,type,path) {

    var vid=document.getElementById(id);
    vid.innerHTML+='<source src="'+path+'" type="'+type+'">';
}

Upvotes: 0

Sophie
Sophie

Reputation: 800

To create multiple sources, you need to have source elements inside the video tag rather than using the video's source attribute. Use:

sourceElement=document.createElement("source")
sourceElement.source=someSource
sourceElement.type=someType
changeStuff.appendChild(sourceElement)

Upvotes: 1

Related Questions