jQuery YouTube TubePlayer Plugin v1.1.6 / Jun 4, 2013


Update: HTML5 Support!

13th Feb 2011

HTML5 goodness! Last year, YouTube introduced an HTML5 based implementation of their embedded player. With the proliferation of mobile devices, the increasing popularity of Apple's iPad, and Apple's stringent requirements around the use of Flash, access to control the HTML5 player has been in great demand. This implementation was first provided for simple embeds and offered as a trial-service on YouTube itself.

Just last month, however, YouTube announced developer access to this HTML5 version of the player. The API was of course created in line with what they had set out for their original JavaScript Player API, which meant that the general pattern and structure that the TubePlayer plugin was maintained; the only difference was around the instantiation of the player itself.

So, what's so great about the YouTube HTML5 player, anyway? Well, basically iPad/iPhone support, enhancemened performance, optimized resource usage, conforming to standards and end user experience. Check this great article on the advantages of the standards based video implementation in HTML5. While I am excited and enthused about providing a plugin that provides iOS (iPad/iPhone) support, i'm disappointed to have to tell you that with the player still in labs mode the player still has some kinks. In addition to the occasional bug, mobile development adds additional complexities. An example is with the potential fees involved in streaming video, Apple dictates that the user must initiate playback, essentially removing possibilities for auto-playing videos in a playlists. For more information, see this forum thread.

The updated TubePlayer plugin takes advantage of HTML5 where possible. A new attribute iframed can be set to true or false depending on whether the iframe player should be prioritized. SWFObject is not strictly a requirement anymore, however TubePlayer has been created such that if the browser does not support HTML5 video, the flash player will be used instead. Anyone upgrading from previous versions of the TubePlayer plugin, all you have to do is replace your jQuery.tubeplayer.js file with the updated code. There is no need to worry about your implementation, as everything is backwards compatible.

Overview

YouTube broke 2 billion views a day just a couple of months back. I have played around with the API for two and a half years in various capacities, but I always stopped at the flash level of the chromeless player. Even though I managed to work through the AS3 implementation, I didn't want to have to go through the pain of designing an interface for a player - I really wanted to play with the API itself.

I recently took a look at the updates to the YouTube API, and I was excited to see that the embeddable player is now controllable through the JavaScript API. As a result I threw it into an example that I created showcasing my other plugin, the jQuery Radmenu plugin. I wanted to have access to the player state change (so I could tell when the player had finished playing the active video) and as a result was capable of creating a sort of 'YouTube wheel' that just continuously plays.

All of my implementations of the YouTube API have been around the creation of playlists and/or stringing specific videos outside of the standard YouTube playlist implementation. The player is the integral part since you need to have a hook when the player has ended to queue up the next video.

Basically this jQuery plugin implements the YouTube Player API pretty much to spec. I've omitted some functions but believe I have captured most of the functionality a developer will need to implement a youtube player. The kind of things that this plugin allows the developer to simply get done are --

  1. Play: the player & a specific video
  2. Pause the player
  3. Stop the player
  4. Seek to a particular point within a video
  5. Mute and Unmute the player & learn if the player is muted
  6. Get and set the volume of the player
  7. Get and set the video quality
  8. Destroy the player
  9. Friendly functions for player state changes --
    1. onPlayerUnstarted
    2. onPlayerEnded
    3. onPlayerPlaying
    4. onPlayerPaused
    5. onPlayerBuffering
    6. onPlayerCued

If you have any comments, suggestions, or need/want help implementing this plugin - please feel free to email me @ ntikku@gmail.com or tweet me @ntikku . Also, if you do end up implementing this plugin, I would greatly appreciate it if you would send a link over - I'd love to see it in action!

Thanks,
Nirvana Tikku

Quick Start Guide

 
1     Create a container for your player

<html>	
<body>
	<div id='youtube-player-container'> </div>
</body>
</html>
			

 
2     Include the JavaScript

<script type='text/javascript' src='{your_path_to}/jQuery.tubeplayer.min.js'></script>
			

 
3     Initialize the YouTube Player in JavaScript

jQuery("#youtube-player-container").tubeplayer({
	width: 600, // the width of the player
	height: 450, // the height of the player
	allowFullScreen: "true", // true by default, allow user to go full screen
	initialVideo: "DkoeNLuMbcI", // the video that is loaded into the player
	preferredQuality: "default",// preferred quality: default, small, medium, large, hd720
	onPlay: function(id){}, // after the play method is called
	onPause: function(){}, // after the pause method is called
	onStop: function(){}, // after the player is stopped
	onSeek: function(time){}, // after the video has been seeked to a defined point
	onMute: function(){}, // after the player is muted
	onUnMute: function(){} // after the player is unmuted
});
			

 
4     Hook the tubeplayer's events to any elements you want to use as triggers

<a href="#" onClick='jQuery("#youtube-player-container").tubeplayer("play")'> 
	Play video in player
</a>
<a href="#" onClick='jQuery("#youtube-player-container").tubeplayer("pause")'> 
	Pause player 
</a>
<a href="#" onClick='jQuery("#youtube-player-container").tubeplayer("stop")'> 
	Stop player 
</a>
<a href="#" onClick='jQuery("#youtube-player-container").tubeplayer("mute")'> 	
	Mute player 
</a>
<a href="#" onClick='jQuery("#youtube-player-container").tubeplayer("unmute")'> 
	Unmute player
</a>
			

Options / Defaults

In addition to this page, be sure to check out the YouTube JavaScript API Reference if you aren't familiar with it.


The plugin's defaults are --

var defaults = {
	// Plugin init params
	width: 425, // the width of the player
	height: 355, // the height of the player
	allowFullScreen: "true", // true by default, allow user to go full screen
	initialVideo: "DkoeNLuMbcI", // the video that is loaded into the player
	start: 0, 
	preferredQuality: "default",// preferred quality: default, small, medium, large, hd720
	showControls: 1, // whether the player should have the controls visible, 0 or 1
	showRelated: 0, // show the related videos when the player ends, 0 or 1 
	autoPlay: false, // whether the player should autoplay the video, 0 or 1
	autoHide: true, 
	theme: "dark", // possible options: "dark" or "light"
	color: "red", // possible options: "red" or "white"
	showinfo: false, // if you want the player to include details about the video
	modestbranding: true, // specify to include/exclude the YouTube watermark
	// the location to the swfobject import for the flash player, default to Google's CDN
	wmode: "transparent", // note: transparent maintains z-index, but disables GPU acceleration
	swfobjectURL: "http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js",
	loadSWFObject: true, // if you include swfobject, set to false
	// HTML5 specific attrs
	iframed: true, // iframed can be: true, false; if true, but not supported, degrades to flash
	// Player Trigger Specific Functionality
	onPlay: function(id){}, // after the play method is called
	onPause: function(){}, // after the pause method is called
	onStop: function(){}, // after the player is stopped
	onSeek: function(time){}, // after the video has been seeked to a defined point
	onMute: function(){}, // after the player is muted
	onUnMute: function(){}, // after the player is unmuted
	// Player State Change Specific Functionality
	onPlayerUnstarted: function(){}, // when the player returns a state of unstarted
	onPlayerEnded: function(){}, // when the player returns a state of ended
	onPlayerPlaying: function(){}, //when the player returns a state of playing
	onPlayerPaused: function(){}, // when the player returns a state of paused
	onPlayerBuffering: function(){}, // when the player returns a state of buffering
	onPlayerCued: function(){}, // when the player returns a state of cued
	onQualityChange: function(quality){}, // a function callback for when the quality of a video is determined
	// Error State Specific Functionality
	onErrorNotFound: function(){}, // if a video cant be found
	onErrorNotEmbeddable: function(){}, // if a video isnt embeddable
	onErrorInvalidParameter: function(){} // if we've got an invalid param
});

width

Assign the width of the player. By default this is at 425px.

height

Assign the height of the player. By default this is at 355px.

allowFullScreen

True or False, depending on if you want to enable the full screen button.

initialVideo

Assign a YouTube video id for the initial video to be loaded upon player initialization.

preferredQuality

Options: "default", "small", "medium", "large", "hd720". "default" is the plugin's default value.

showControls

This attribute will enable controls in the player, and is only available in the case of the iframe player. Values can be true or false.

showRelated

Whether the player should load related videos once playback of the initial video starts Values can be true or false.

autoPlay

This attribute will autoplay upon load, and is only available in the case of the iframe player. Values can be true or false.

autoHide

Whether the video controls will automatically hide after a video begins playing Values can be true or false.

theme

Sets the color of the overall player. Values can be "dark" or "light". Default is "dark" as per YouTube's spec.

color

Sets the color of the progress bar. Values can be "red" or "white". Default is "red" as per YouTube's spec.

showinfo

Whether or not to show the loaded videos details. Values can be true or false.

modestbranding

This parameter can be used to include/exclude the YouTube watermark. Values can be true or false.

swfobjectURL

The swfobject dependency is for the flash based implementation of the player. By default the url is specified to the Google CDN location for swfobject version 2.2. You can override this if you want to use a local version.

loadSWFObject

If you want to include the swfobject in a minified file, or would rather that the TubePlayer plugin not load the swfobject, set this to false. If not, if using the flash player, the player will only be initialized after the script has been imported.

iframed

This attribute is a boolean, true/false. If true, TubePlayer will prioritize the HTML5 implementation of TubePlayer (provided it's available), over the flash based player. If false, only the flash player will be used.

Trigger Events

onPlay

After the player triggers a play event, the onPlay method is called and passed the id that was played. This can come in handy in situations where you may want to track / utilize the play event and possibly hook in your analytics.

onPause

Similar to onPlay, onPause is called after the player is paused.

onStop

Ditto, onStop is after the player has been stopped.

onSeek

Convenience method while seeking. This method is passed the seekTime. Most often used by a slider or some similar interface.

onMute

For whatever reason if you want to do something when the player is muted.

onUnMute

Ditto, if you want to do something when the player is unmuted.

Player Events

onPlayerUnstarted

This method is called when the state of the player is cued, but has not been started.

onPlayerEnded

This method gets triggered when the video has finished playing.

onPlayerPlaying

As soon as the player starts playing, this method is called right after.

onPlayerPaused

When the state of the player is paused this method is called.

onPlayerBuffering

Whilst the player is buffering, this method is called.

onPlayerCued

After the player is cued up with a video.

onQualityChange

Whenever the video quality is determined, this callback is invoked.

Errors

onErrorNotFound

If the video is not found, this method will get called.

onErrorNotEmbeddable

If the video you have entered is not embeddable, this method will get called.

onErrorInvalidParameter

If the player wasn't init'd properly, possibly due to a bad VideoID

Events

There are a set of events that are bound to TubePlayer upon initialization. These events can be called directly by passing in a string argument, the event, to trigger the event on the menu. Some events may require arguments, in which case pass the arguments as well. Note: Unless specified, all triggers return the player meaning you can continue to utilize chaining.

Cue

Cue a video specified by videoId. The player uses the quality setting defined upon initialization to cue the video.
jQuery("#youtube-player-container")
      .tubeplayer("cue", "videoId");

Play

Play has three different implementations. The first, is to play the active video, if you do not specify a parameter.

If you specify a parameter, and that parameter is a string, then the player will cue and play the specified video.

Lastly, if you specify a parameter, and that parameter is an OBJECT, you will have the ability to pass in the id and the start time -- {id: "",time:""}.
jQuery("#youtube-player-container")
      .tubeplayer("play");
      or
jQuery("#youtube-player-container")
      .tubeplayer("play", "DkoeNLuMbcI");
      or
jQuery("#youtube-player-container")
      .tubeplayer("play", {      id: "DkoeNLuMbcI",      time: 20 });

Pause

Simply pauses the player.
jQuery("#youtube-player-container")
      .tubeplayer("pause");

Stop

Stops the player from loading.
jQuery("#youtube-player-container")
      .tubeplayer("stop");

Seek

Specify a time to seekTo and this method will skip the player to the specified time.
jQuery("#youtube-player-container")
      .tubeplayer("seek", 100);

Mute

Mute the player.
jQuery("#youtube-player-container")
      .tubeplayer("mute");

Unmute

Unmute the player. Currently, potentially due to an API bug, I set the value of the volume to 100, since even though the player says that it has been unmuted, it does not play.
jQuery("#youtube-player-container")
      .tubeplayer("unmute");

isMuted

Returns true or false depdending on whether the player is muted.
jQuery("#youtube-player-container")
      .tubeplayer("isMuted");

Volume

Volume has two variations - getter and setter. Simply pass in "volume" to get the volume {0,100}, and pass a parameter within {0,100} to specify a new volume.
jQuery("#youtube-player-container")
      .tubeplayer("volume");
      or
jQuery("#youtube-player-container")
      .tubeplayer("volume", 25);

Quality

Quality also has two variations - getter and setter. If you want to get the current quality of the player, pass in "quality" without params. If you want to set the quality, based off of the available quality levels, pass that in as a string parameter.
jQuery("#youtube-player-container")
      .tubeplayer("quality");
      or
jQuery("#youtube-player-container")
      .tubeplayer("quality", "medium");

Data

Typically you will want to access the information thats available from the player. The data method returns an object with the information of the player. As YouTube typically shows, you can create a setInterval and use this method to retrieve the information you will want per time period. The information that is returned is:
bytesLoaded, bytesTotal; startBytes; state; currentTime; availableQualityLevels; the 'duration' and the 'videoURL' of the active video
jQuery("#youtube-player-container")
      .tubeplayer("data");

Player

Returns the YouTube Player object (the actual embedded player). This is better to use for performance in setInterval's that want to poll the player to get the duration etc. This requires that you treat the 'player' object that is passed back, as the ytplayer that the YouTube API specifies. Look at the documentation for more detail.
jQuery("#youtube-player-container")
      .tubeplayer("player");

Size

Update the size of the player. This event requires passing an object as an argument, that has the width and the height specified. Note that under the hood, the player's css is updated using the object specified by using jQuery().css({}), meaning that you can pass in additional CSS parameters if you wish and upon size updates, the specified css changes will also be made.
i.e. { width: 300, height: 200, border: "2px solid blue" }
jQuery("#youtube-player-container")
      .tubeplayer("size", { width: 300, height: 200 });

Destroy

Destroy the embed (remove it), unbind evertyhing on the player container & remove local storage.
jQuery("#youtube-player-container")
      .tubeplayer("destroy");

Player event listeners

The YouTube Player has three different event listeners subscribed: stateChange, onError and onPlaybackQualityChange. In addition to this, there is an extra function that you can latch on to after the player is 'ready'. It is recommended not to play with the stateChange, onPlaybackQualityChange or onError functions, since they have been setup to trigger the various helper methods (onPlayerUnstarted, onPlayerEnded, etc).. that make the plugin so convenient.

$.tubeplayer.defaults.afterReady

After the play is ready (and has been completely loaded) the jQuery player object is passing into the 'afterReady' function.
$.tubeplayer.defaults.afterReady
	= function($player){}

$.tubeplayer.getPlayers()

A means to get all the players that have been instantiated.
$.tubeplayer.getPlayers()

Legal

MIT License

File details / download

v1.1.6

Production - 9.8kB ( Download )
Minified with Google Compiler

Development - 19kB ( Download )
Commented


GitHub - http://github.com/nirvanatikku/jQuery-TubePlayer-Plugin

Find TubePlayer Useful?


Tip

Changelog

More up to date information: see GitHub

v1.1.0 - Oct 1, 2012

Enabled ES5 'strict' mode
Stricter equality checks / improve code
Multiple player support - appropriate randomization by use of GUIDs
Fix event handler binding on the player objects (both flash based and html5 enabled) - jQuery.tubeplayer.events
Perform appropriate cleanup when destroying tubeplayer

v1.0.4 - Nov 12, 2011

Bug fixes for parsing videoID
Support added for 'loop' parameter and annotations (iv_load_policy)

v1.0.3 - Aug 14th, 2011

Added theme and color support - dark/light with red/white
Added 'start' attribute - default 0
Added 'showinfo' attribute - default false
Added 'modestbranding' attribute - default true
Updated showControls, showRelated, autoPlay and autoHide to boolean from int

v1.0.2 - Aug 3rd, 2011

Add support for 'autoHide' parameter
'loadSWFObject' attribute allows user to specify their swfobject inclusion

v1.0.1 - May 14th, 2011

IE 7 and 8 fixes
Simplify dependency by utilizing Google CDN for swfobject instead of requiring additional include
Added videoEmbedURL and videoID to "data" object
Added "videoId" convenience method
New onErrorInvalidParameters method to handle final error case
Added support for 'showControls' and 'showRelated' player attributes
Enhanced multiple player support for iframe/html5 player
New public method to get all players jQuery.tubeplayer.getPlayers()
Fixed unmute - uses volume before muted now
Special thanks to @Branden Smith for the first few fixes

v1.0.0 - Feb 13th, 2011

Note: This update is completely backwards compatible
Support for HTML5 - IFRAME embedded player
HTML5 by default now, if not supported will degrade to Flash player
Added 'autoplay' and 'controls' properties for player init

v0.9.4 - Sept 5th, 2010

New event: 'size'; Now you can modify the player's size
Add player 'wmode' default as transparent, to prevent z-index issues in IE (thanks @Daniel Brouse)

v0.9.3 - Aug 20, 2010

Fixed onError Handlers

v0.9.2 - Aug 10, 2010

Added 'player' method, to get direct access to the youtube player

v0.9.1 - July 30, 2010

Multiple player support
Added 'onQualityChange' callback to defaults

v0.9.0 - July 24, 2010

Embed the API driven Flash YouTube Video Player - init/destroy
Control the player - cue, play, pause, stop, seek, volume control, quality control and data retreival
Give developer controls after each event is triggered
Provide developer with state change friendly events (i.e. instead of state == -1, onPlayerUnstarted)
Hooks for 'afterReady', 'stateChange', 'onError' and 'qualityChange' for the player
Convenience methods for errors - onErrorNotFound, onErrorNotEmbeddable
Browser support tested: Firefox 3.5+, Chrome 5, Opera 10, Safari 5, IE6+

Frequently Asked Questions

What version of jQuery is TubePlayer dependent on?

jQuery 1.3.2+

What else is TubePlayer dependent on?

SWFObject.     As per YouTube's suggestion, the best flash embedding plugin is the SWFObject. As a result this plugin is dependent on it. There are several reasons for this, but simply put it guarantees cross browser support, particularly in Internet Explorer. Note, with the updated support utilizing the iframe/HTML5 solution, the swfobject import is not used. However, in order to degrade the TubePlayer plugin, where HTML5 is not supported, the flash based player will require swfobject.

Fork me on GitHub