Interacting with HTML5 Video Players

HTML5 video players are incredibly useful, enabling developers to display video on non-flash devices (I’m looking at you, Apple). It’s really simple to get started with HTML5 video, but when you want to do something more complicated, there’s not much documentation. Thankfully, it’s really quite simple, and this article will show you how to use the HTML5 video JavaScript API to interact with the videos.

Basic video


This is the HTML:

<video id="firstvideo" style="width:100%" controls>
	<source src="http://mirrorblender.top-ix.org/peach/bigbuckbunny_movies/big_buck_bunny_480p_stereo.ogg" >
	<source src="http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_640x360.mp4" />
</source></video>

This is your standard HTML5 video player, with the standard browser video controls. The video has multiple sources so browsers that only support certain codecs (FireFox and Ogg for example) get the right video.

Let’s say you want the video to start when you click a button. That’s pretty easy, and looks like this:

var firstvideo = document.getElementById('firstvideo');
var playButton = document.getElementById('playfirstVideo');
playButton.addEventListener('click', function(e) { 
	firstvideo.play();
});
//jQuery version
$('#playfirstVideo').on('click', function(e) {
	$('#firstvideo').play();
});


And if you want to pause it:

var stopButton = document.getElementById('stopfirstVideo');
stopButton.addEventListener('click', function(e) { 
	firstvideo.pause();
});
//jQuery version
$('#stopfirstVideo').on('click', function(e) {
	$('#firstvideo').pause();
}


Subscribable events

That’s cool, you can interact with the element through JavaScript. If you’re a fan of the regular video controls, you can still access events fired by the video. The main ones you’ll be interested in are:

  • play – triggered when the video starts playing
  • playing – triggered whilst the video is playing
  • canplay – triggered when the video has been loaded and it can be played
  • pause – triggered when the video is paused
  • ended – triggered when the video has finished

There are lots of others too, a full list can be seen on the W3C demo for HTML5 video. These include events triggered when the video is seeked (skipped forward or backwards in time) and when the time on the video has changed.

It’s simple to hook these up using event listeners to see what’s going on.

Video state:

Try it out using this video, watching the label which says which event was fired last.

	var secondvideo = document.getElementById('secondvideo');
	var statelabel = document.getElementById('videoState');
	secondvideo.addEventListener('play', function(e) { // Repeat this for other events
		// The video is playing
		statelabel.innerHTML = "Playing";
	});
	// jQuery example
	var statelabel = $('#videoState');
	$('#secondvideo').on('play', function(e) { // Repeat this for other events
		// The video is playing
		statelabel.html("Playing");
	});

That's the basics, from there you can use the timing event to make a caption system (tag words with data elements and mark them when their time hits in the video).

What about YouTube?

With YouTube and other embedded video players there's no direct access to the video element, which makes interacting with videos in the way shown above very difficult.
Thankfully, the kind folks at Google have thought of this and provided an API to help us through. The whole documentation is on YouTube developers and there's a great player demo, but here's the gist of it.

There's a few gotchas you need to be aware of:

  1. You've got to be using a served web page, local files won't work.
  2. If you're trying to interact more than one YouTube embed on a page, you will need to address each one individually with unique IDs, otherwise the browser won't know which video to interacti with

Got it? Great, let's head into the code.
This first section, is the embed code needed to include the video in the page. This should be standard YouTube embedding stuff.

// The element that the player will be inserted into
<div id="ytplayer"></div>
<script>
// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
 
// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
  player = new YT.Player('ytplayer', {
    height: '390',
    width: '640',
    videoId: 'g8evyE9TuYk',
    events: {
      'onStateChange': "onytplayerStateChange"
    }
  });
}</iframe></script>

Video state:

That's your YouTube video, now we need to subscribe to the events N.B. there's no need to subscribe to the onYouTubePlayerReady event as you've effectively done this when the API loads

function onytplayerStateChange(e) {
	document.getElementById('ytvideoState').innerHTML = e.data;
}
// jQuery version
function onytplayerStateChange(e) {
	$('#ytvideoState').html(e.data);
}

As the state changes, a different value appears at the bottom. These are: unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5). From there you can access any function of the YouTube JavaScript API, which mimics the HTML5 spec with a few small changes, such as the play command is playVideo() instead of just play(). Take a look at the documentation for full details about what you can do.

Vimeo too?

Yes, Vimeo can do this too. The API is similar to YouTube, but isn't quite as simple without their Frogaloop library, so have a look at their documentation for the Vimeo JavaScript API.

Summary

So, there you have it, a few bits of code to control different types of HTML5 video that are common on the web. They're really useful for counting the number of views of a video, captions, and generally making videos more interactive. Let me know what uses you come up with for it in the comments.

0saves
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Steve Workman

Steve Workman is the Head of Web Engineering at Yell. He is also an organiser for London Web Standards is an occasional public speaker, talking about web performance and web standards

More Posts - Website - Twitter - Google Plus

Tags: , , , , ,

2 Comments

  1. Lyle said:

    Steve,
    I’ve been starting to play with html5 video and your post looks to be very useful but I think there are some problems with the first part.
    Only the first second of the video plays on your web page in both FF and Chrome.
    And when I built an html doc from your code I found a couple problems.
    The first I could fix, both the javascript and the jquery click receivers are missing the close );
    The second problem is out of my league, neither version of the click seem to work after being put into a document.
    After fixing the closes the Jquery doesn’t throw an error (I do have the Jquery call at the top)
    The javascript version gives “Uncaught TypeError: Cannot call method ‘addEventListener’ of null ”
    Which I’m not sophisticated enough to understand.

    Thanks!

    Lyle

  2. Lyle said:

    Oop!
    Looks like mos of the problem is the video itself is SLOW

Leave a response