Changing HTML 5 video with JavaScript or jQuery

02 May, 2014 by Tom Elliott

There are many reasons why you might want to change a HTML 5 video dynamically. For example when clicking video thumbnails in a gallery, or playing a new video clip once the current video has reached the end. The video tag is now supported by the vast majority of browsers and without the need for any 3rd party plugins. If you still need to support IE 8 or below however, this would require alternative methods such as Flash video fallback.

This post runs through the code required to change a HTML 5 video when a link is clicked. Examples are given in both JavaScript and jQuery and we will also look at how to change the poster image attribute. The code has been tested in all major browsers IE 9-11, Chrome, FireFox and Safari along with iOS and Android devices

.mp4 video encoding with the H.264 codec is required for HTML 5 video. This is the most widely supported HTML 5 format, compatible with the vast majority of modern browsers including Internet Explorer 9, IE 10, IE 11, FireFox, Chrome and Safari along with Android devices and iOS. The only modern browser that does not support .mp4 at this stage is Opera (more on this later).

The HTML

Let’s take a look at some typical code for a basic HTML 5 video.

<!DOCTYPE html>
<head></head>
<body>
<p><a href="#" id="videolink1">Change video</a></p>
<video id="videoclip" controls="controls" poster="images/cover.jpg" title="Video title">
  <source id="mp4video" src="media/video1.mp4" type="video/mp4"  />
 </video>
</body>
</html>

The ‘video’ tag has been given an id ‘videoclip’ along with a poster image and a single source .mp4 file. The source tag has been given an id ‘mp4video’ which will allow us to easily target and change the source ‘src’ link attribute direct. This method of changing the video is better than over alternatives such as modifying the source HTML as highlighted by the W3C:

To change what is playing, just use the src attribute on the media element directly… Generally, manipulating source elements manually after the document has been parsed is an unnecessarily complicated approach.

A ‘Change video’ link will be used to trigger our video update. Also note the !DOCTYPE html being used for HTML 5 document declaration.

Changing HTML 5 video via JavaScript

Let’s take a look at the code required to change a video through regular JavaScript. It is important to include this somewhere after the video tag and before the closing body tag, otherwise it will try and access elements in the DOM that haven’t loaded yet.

<script type="text/javascript">
var videocontainer = document.getElementById('videoclip');
var videosource = document.getElementById('mp4video');
var newmp4 = 'media/test/whystudy.mp4';
var newposter = 'images/video-cover.jpg';

var videobutton = document.getElementById("videolink1");

videobutton.addEventListener("click", function(event) {
	videocontainer.pause();
	videosource.setAttribute('src', newmp4);
	videocontainer.load();
	//videocontainer.setAttribute('poster', newposter); //Changes video poster image
	videocontainer.play();
}, false);

</script>

A set of variables are first created which store the video and source tag ID’s as well as the paths to the video cover image and the video .mp4 file we’re going to switch. A ‘click’ event handler is setup on the ‘Change video’ link and upon trigger, we pause the current video and then change the src attribute of the source tag using setAttribute. The video is then loaded via the load() command and started using play(). If you don’t want the video to played automatically, remove the videocontainer.play(); line.

The video cover image can be changed using videocontainer.setAttribute('poster', 'path-to-image');. This is disabled in the code above as the video is played automatically and you would only see the poster for a fraction of a second. Note, the video poster image update does not work reliably within IE 9.

Changing HTML 5 video via jQuery

If you’d rather use jQuery over regular JavaScript, here’s the code to update the video.

<script type="text/javascript">
$(document).ready(function() {
  var videoID = 'videoclip';
  var sourceID = 'mp4video';
  var newmp4 = 'media/video2.mp4';
  var newposter = 'media/video-poster2.jpg';

  $('#videolink1').click(function(event) {
    $('#'+videoID).get(0).pause();
    $('#'+sourceID).attr('src', newmp4);
    $('#'+videoID).get(0).load();
     //$('#'+videoID).attr('poster', newposter); //Change video poster
    $('#'+videoID).get(0).play();
  });
});
</script>

Don’t forget to add the jQuery file somewhere in the head tag:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

The jQuery is similar to the JavaScript. A document ‘ready’ event listener has been added and we can place the code above the video tag in the header. One of the key differences with using jQuery to change our video is that we need to target the video container through an additional get(0) command.

Supporting Opera

As mentioned earlier in the post, .mp4 is now supported in all modern browsers (including IE 9+) except Opera. In many cases, you might feel the user base of Opera is too small (worldwide Opera accounts for just over 1% of the market) and not worth the additional effort of creating a .webm or .ogg version of the HTML 5 video. If you do want to support Opera however, it should be easy to change the src of the video source based on basic browser detection:

if (navigator.userAgent.indexOf("Opera") > 0 ) {
   videosource.setAttribute('src', 'path-to-webm-or-ogg-file');
} else {
   videosource.setAttribute('src', 'path-to-mp4-file');
}

Troubleshooting the video

If you’re having problems playing the video, try opening the .mp4 file path direct in the browser. If it still doesn’t play, there’s probably an encoding issue or the .mp4 MIME type is not setup on the server.

If you’re concerned about the poster image not displaying in IE 9, adding the parameter preload="none" to the video tag displays the image on video load, but the poster update is still buggy when trying to change the video.



Detect HTML 5 video play & pause with jQuery »


17 Comments

  • Sindhuja says:

    Nice post. saved my head.thanks

  • David says:

    Very informative post. I have a question, though. Why do you have to use the .get() function in Jquery? Does it have something to do with the url? Or some sort of index?

    • Ben N says:

      Well David, jQuery return an array object. Even if you’re selecting an element, it still array. So, it’s a kind of $(selector)[0], in a more-elegant way.

  • Thanushan says:

    What if you have to link from a different page? how can we modify the code to work.

    thanks

  • Bhumi says:

    Hello,

    I have multiple video tag and want to get that longer video from multiple and when it ends want to execute code.

    How can i do it?

    Thanks,
    Bhumi

    • Anonymous says:

      var video = document.getElementById(‘video’); //video-tag
      var source = document.getElementById(‘source’); //source-tag

      video.addEventListener(‘ended’, function () {
      source.setAttribute(‘src’, ‘yourNewSource.mp4’);
      video.load();
      video.play();
      });

      Thank me later 🙂

  • Jim G says:

    Thank you! My only question is I have a result set printing on the html using php/MySQL. How do I make “newmp4” = any of the urls in the result set the user might click?

  • rod russell says:

    In order to change multiple videos dynamically couldn’t you use simplexml and include array using the children to reference each vid

  • kumar says:

    How to play html5 video in IE9 browser is there any solution to play in IE9.We have used mp4/webm/ogg formats but the video tags are not playing in IE9 broswer.

  • jyosna says:

    how to playing video and audio with in one button using javascript

    • Arun says:

      Give a class name to your perticular div tag and add click event and put your video and audio play code inside click event both will play simultaniously….

  • Chris says:

    How you do this where you have an array of say 10 videos in a JSON file?

  • Daniel Parsons says:

    Good post. Well explained and a good starter tutorial for those new to HTML5 video. I enjoyed the tutorial.

    Thanks

  • Thanks, Tom, for this highly helpful post about replacing HTML5 video source URL dynamically using JavaScript/jQuery. Saved a lot of time.

  • Jesse says:

    would it work to encapsulate the js/jquery in something like

    function switchVid(newMP4, newPoster {
    …stuff
    }

    to pass the urls of the vid and poster using onClick=”switchVid(‘somethin.mp4’, ‘something.jpg’)” in an a href tag?

  • Gaurav Gajbhiye says:

    Hello,
    I wanted play my h264 live stream on ie, i am loading my stream using setAttribute for src but after play more than 3 stream ie giving me error invalid source. Does anyone know about it.

  • benny says:

    The video tag supports more than one src tag.
    I testet following successfull:

    $(“#mp4video”).attr(“src”, “mabe-some-dynamic-name-here.mp4”);
    $(“#oggvideo”).attr(“src”, “mabe-some-dynamic-name-here.ogg”);

    Like this you don’t have to check which browser is calling the page.