MediaElement.js is a JavaScript library that gives you video and audio play capabilities based on the HTML5 specifications. It includes a Flash wrapper for browsers that don’t support certain codecs or that don’t support the HTML5 <audio> and <video> tags.
MediaElement.js has come packaged with WordPress core since version 3.6. The MediaElement.js API page gives a good introduction to installing the library and including it in a project. However, examples on how use and extend it are lacking. The easiest way to extend MediaElement is to connect with the event listeners that it includes.
Initializing MediaElement
There are three ways to initialize MediaElement:
jQuery
$('video').mediaelementplayer();
This is the most basic way to initialize it, and works well if you have a large number of videos and don’t need to reference them very often. You can still change any of the options by passing arguments to mediaelementplayer(), but to refer to the player again you’ll have to use jQuery to search the DOM and find the element(s), which can be slow.
Create a MediaElement
var x = new MediaElement( 'id', {} );
This initializes the media component of MediaElement.js, without adding the player.
Create a MediaElementPlayer
var x = new MediaElementPlayer( '#id', {} );
This initializes MediaElement for an element, and gives you a variable which you can easily reference later (we’ll explore this in the example below). I’ve found that this is the most effective way to work with MediaElement.
Callbacks
This is where you can add on to the functionality of the media player. When initializing the player, there is a “success” callback which is where code can be added once the player is initialized. Inside the success callback function, you can add listeners to any of the events that MediaElement.js provides (see the API documentation for a list of the events):
[snippet slug=mediaelement-callbacks lang=js]
An Example
The most recent project I did with MediaElement.js involved a video with a custom overlay. The overlay showed different text before the video started, when it was paused, and when it was finished. To accomplish this, I wrote markup for the video player to be inside the overlay container, with the overlay text following it:
[snippet slug=mediaelement-example-markup lang=html]
and styled them:
[snippet slug=mediaelement-example-styling lang=cs]
Once our markup for the media player and overlays are in place, we’ll start the media player and add event listeners to show the appropriate overlays:
[snippet slug=mediaelement-example-js lang=js]
Conclusion
When displaying media on a website, MediaElement is a very useful tool.
Hopefully this guide will help you start adding on to its default functionality and give you some ideas to expand on.