changing source on html5 video tag changing source on html5 video tag javascript javascript

changing source on html5 video tag


I hated all these answers because they were too short or relied on other frameworks.

Here is "one" vanilla JS way of doing this, working in Chrome, please test in other browsers:

http://jsfiddle.net/mattdlockyer/5eCEu/2/

HTML:

<video id="video" width="320" height="240"></video>

JS:

var video = document.getElementById('video');var source = document.createElement('source');source.setAttribute('src', 'http://www.tools4movies.com/trailers/1012/Kill%20Bill%20Vol.3.mp4');video.appendChild(source);video.play();setTimeout(function() {      video.pause();    source.setAttribute('src', 'http://www.tools4movies.com/trailers/1012/Despicable%20Me%202.mp4');     video.load();    video.play();}, 3000);


Modernizr worked like a charm for me.

What I did is that I didn't use <source>. Somehow this screwed things up, since the video only worked the first time load() was called. Instead I used the source attribute inside the video tag -> <video src="blabla.webm" /> and used Modernizr to determine what format the browser supported.

<script>var v = new Array();v[0] = [        "videos/video1.webmvp8.webm",        "videos/video1.theora.ogv",        "videos/video1.mp4video.mp4"        ];v[1] = [        "videos/video2.webmvp8.webm",        "videos/video2.theora.ogv",        "videos/video2.mp4video.mp4"        ];v[2] = [        "videos/video3.webmvp8.webm",        "videos/video3.theora.ogv",        "videos/video3.mp4video.mp4"        ];function changeVid(n){    var video = document.getElementById('video');    if(Modernizr.video && Modernizr.video.webm) {        video.setAttribute("src", v[n][0]);    } else if(Modernizr.video && Modernizr.video.ogg) {        video.setAttribute("src", v[n][1]);    } else if(Modernizr.video && Modernizr.video.h264) {        video.setAttribute("src", v[n][2]);    }    video.load();}</script>

Hopefully this will help you :)

If you don't want to use Modernizr , you can always use CanPlayType().


Your original plan sounds fine to me. You'll probably find more browser quirks dealing with dynamically managing the <source> elements, as indicated here by the W3 spec note:

Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, just use the src attribute on the media element directly, possibly making use of the canPlayType() method to pick from amongst available resources. Generally, manipulating source elements manually after the document has been parsed is an unncessarily[sic] complicated approach.

http://dev.w3.org/html5/spec/Overview.html#the-source-element