Steve Workman's Blog

Interacting with HTML5 Video Players

Posted on by Steve Workman About 4 min reading time

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:

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();
});

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();
}

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:

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
<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);
<div></div>
// 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.