Making a Custom YouTube Video Player With YouTube’s APIs

Making a Custom YouTube Video Player With YouTube’s APIs

Video presentations are a great addition to any product page. With a presentation you can showcase your product’s features without making the visitor read through long paragraphs of text. But apart from producing the video, you still need to manually convert it and find (or code) some sort of flash player that will display it on your site.

The other possible path is that you upload it to a video sharing site such as youtube, but you are going to have a rough time trying to incorporate the player into your design.

Luckily for us, YouTube does provide a solution to this problem – their chromeless player (a stripped down version of the regular embeddable player), which allow you to build and style your own custom controls. This way you have both a quick and secure way to include videos in your pages, and the freedom to customize any way you might want to.

The Idea

Today we are going to make a jQuery plugin which uses YouTube’s chromeless player, and creates our own set of minimalistic controls, which allows for perfect integration with your designs. The supported controls include a Play/Pause/Replay button, and a clickable progress bar.

The plugin is going to use YouTube’s gdata api to determine whether embedding has been allowed for the video, and fetch extensive information about it, such as title, description, tags, screenshots & more, which you can use to improve the plugin.

Using the plugin to embed videos is extremely easy:

// Embed a video into the #player div:
$('#player').youTubeEmbed('http://www.youtube.com/watch?v=u1zgFlCw8Aw');

// Chaining is also supported:
$('#player').youTubeEmbed('http://www.youtube.com/watch?v=u1zgFlCw8Aw');
		.youTubeEmbed('http://www.youtube.com/watch?v=AsdfFdwlzdAw');

You can also specify a width for the embedded video (the height will be calculated automatically depending on the aspect ratio), and choose to disable the progress bar:

$('#player').youTubeEmbed({
	video			: 'http://www.youtube.com/watch?v=u1zgFlCw8Aw',
	width			: 600, 		// Height is calculated automatically
	progressBar	: false		// Hide the progress bar
});

You can grab the plugin from the download button above, and start with the first step.

Step 1 – XHTML

Our plugin depends on jQuery SWFObject to embed the SWF files in the page. Below you can see the combined markup that is generated by both of the plugins.

youtube-player.html

<div class="flashContainer" style="width: 640px; height: 360px;">

	<object height="360" width="640" id="video_26ELpS3Wc4Q" type="application/x-shockwave-flash"
	data="http://www.youtube.com/apiplayer?enablejsapi=1&version=3">

		<param value="always" name="allowScriptAccess">
		<param value="transparent" name="wmode">
		<param value="video_id=26ELpS3Wc4Q&playerapiid=26ELpS3Wc4Q"
		name="flashvars">
		<param value="http://www.youtube.com/apiplayer?enablejsapi=1&version=3"
		name="movie">

	</object>

	<div class="controlDiv play"></div>

	<div class="progressBar">
		<div class="elapsed"></div>
	</div>
</div>

The .flashContainerDiv is dynamically created by the plugin for each video on the page. It is populated with the embed code generated by SWFObject, the .controlDiv (which acts as a play/pause button) and the progress bar.

As mentioned above, the insertion of the player itself is handled by the SWFObject plugin. Depending on the browser, it can output either an object element, or a non-standard embed element for IE. This lifts the burden from us and allows us to concentrate on tasks such as querying YouTube’s APIs and building the player controls.

Custom YouTube Player

Custom YouTube Player

Step 2 – jQuery

The plugin’s code is located in the youTubeEmbed-jquery-1.0.js file. However, before being able to use it, you need to include the latest version of the jQuery library in the page, along with the jQuery SWFObject plugin and lastly script.js, which inserts two videos in the demonstration page and handles the submissions of the preview form.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="jquery.swfobject.1-1-1.min.js"></script>
<script src="youTubeEmbed/youTubeEmbed-jquery-1.0.js"></script>
<script src="script.js"></script>

Before we start digging into the player plugin’s code, lets take a look at a sample response from YouTube’s gdata api. It can give you a lot of useful information about a video, including duration, access control (both of which used by the plugin) and all sorts of additional data such as title, description, tags, screenshots and more.

Sample JSON response

{
    "id": "u1zgFlCw8Aw",
    "uploaded": "2008-03-05T01:22:17.000Z",
    "updated": "2010-07-23T01:02:42.000Z",
    "uploader": "GoogleDevelopers",
    "category": "People",
    "title": "The YouTube API: Upload, Player APIs and more!",
    "description": "Listen to the YouTube APIs and Tools team talk about...",
    "tags": ["youtube", "launch", "api", "engineering"],
    "thumbnail": {
        "sqDefault": "http://i.ytimg.com/vi/u1zgFlCw8Aw/default.jpg",
        "hqDefault": "http://i.ytimg.com/vi/u1zgFlCw8Aw/hqdefault.jpg"
    },
    "player": {
        "default": "http://www.youtube.com/watch?v=u1zgFlCw8Aw",
        "mobile": "http://m.youtube.com/details?v=u1zgFlCw8Aw"
    },
    "content": {
        "1": "rtsp://v4.cache5.c.youtube.com/CiILE..",
        "5": "http://www.youtube.com/v/u1zgFlCw8Aw?f..",
        "6": "rtsp://v3.cache4.c.youtube.com/CiILENy73.."
    },
    "duration": 259,
    "location": "san bruno, ca",
    "rating": 4.3,
    "likeCount": "119",
    "ratingCount": 144,
    "viewCount": 251024,
    "favoriteCount": 164,
    "commentCount": 118,
    "accessControl": {
        "syndicate": "allowed",
        "commentVote": "allowed",
        "rate": "allowed",
        "list": "allowed",
        "comment": "allowed",
        "embed": "allowed",
        "videoRespond": "allowed"
    }
}

All the fields of this response objects are available as properties in the data variable (data.fieldname). You could potentially modify the plugin to show the title with a link to the video page on youtube, or show the rating of the video.

Now lets dive directly into the script’s source code.

youTubeEmbed-jquery-1.0.js – Part 1

(function($){

	$.fn.youTubeEmbed = function(settings){

		// Settings can be either a URL string,
		// or an object

		if(typeof settings == 'string'){
			settings = {'video' : settings}
		}

		// Default values

		var def = {
			width		: 640,
			progressBar	: true
		};

		settings = $.extend(def,settings);

		var elements = {
			originalDIV	: this,	// The "this" of the plugin
			container	: null,	// A container div, inserted by the plugin
			control		: null,	// The control play/pause button
			player		: null,	// The flash player
			progress	: null,	// Progress bar
			elapsed		: null	// The light blue elapsed bar
		};

		try{	

			settings.videoID = settings.video.match(/v=(\w+)/)[1];

			// safeID is a stripped version of videoID,
			// ready for use as a JavaScript function name

			settings.safeID = settings.videoID.replace(/[^a-z0-9]/ig,'');

		} catch (e){
			// If the url was invalid, just return the "this"
			return elements.originalDIV;
		}

		// Fetch data about the video from YouTube's API

		var youtubeAPI = 'http://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc';

		$.get(youtubeAPI,{'q':settings.videoID},function(response){

			var data = response.data;

			if(!data.totalItems || data.items[0].accessControl.embed!="allowed"){

				// If the video was not found, or embedding is not allowed;

				return elements.originalDIV;
			}

			// data holds API info about the video:

			data = data.items[0];

			settings.ratio = 3/4;
			if(data.aspectRatio == "widescreen"){
				settings.ratio = 9/16;
			}

			settings.height = Math.round(settings.width*settings.ratio);

We start by defining our script as a jQuery plugin by adding it as a function to the $.fn object. To make the code easier to follow and read, I put all the elements of the page, such as the control and the progressBar divs in a structure called elements.

After extracting the id of the video (a unique 11 character sequence after the ?v= parameter), we send a JSONP request to youtube’s gdata API. Depending on whether such a video exists, and on whether embedding is allowed on it, we proceed with calculating the aspect ratio. The height of the video is calculated by using this ratio and multiplying it to the width.

youTubeEmbed-jquery-1.0.js – Part 2

			// Creating a container inside the original div, which will
			// hold the object/embed code of the video

			elements.container = $('<div>',{className:'flashContainer',css:{
				width	: settings.width,
				height	: settings.height
			}}).appendTo(elements.originalDIV);

			// Embedding the YouTube chromeless player
			// and loading the video inside it:

			elements.container.flash({
				swf			: 'http://www.youtube.com/apiplayer?enablejsapi=1&version=3',
				id			: 'video_'+settings.safeID,
				height		: settings.height,
				width		: settings.width,
				allowScriptAccess:'always',
				wmode		: 'transparent',
				flashvars	: {
					"video_id"		: settings.videoID,
					"playerapiid"	: settings.safeID
				}
			});

			// We use get, because we need the DOM element
			// itself, and not a jquery object:

			elements.player = elements.container.flash().get(0);

			// Creating the control Div. It will act as a ply/pause button

			elements.control = $('<div>',{className:'controlDiv play'})
							   .appendTo(elements.container);

			// If the user wants to show the progress bar:

			if(settings.progressBar){
				elements.progress =	$('<div>',{className:'progressBar'})
									.appendTo(elements.container);

				elements.elapsed =	$('<div>',{className:'elapsed'})
									.appendTo(elements.progress);

				elements.progress.click(function(e){

					// When a click occurs on the progress bar, seek to the
					// appropriate moment of the video.

					var ratio = (e.pageX-elements.progress.offset().left)/elements.progress.outerWidth();

					elements.elapsed.width(ratio*100+'%');
					elements.player.seekTo(Math.round(data.duration*ratio), true);
					return false;
				});

			}

In the second part of the code, we use the SWFObject plugin to generate the embed code of  the youtube chromeless player. Notice that the id of the video is passed as a flashvar so the player can load it directly. The safeID variable (a JavaScript safe version of the videoid) becomes the value of the id parameter of the to-be generated object element. This way we can later fetch the DOM element by running document.getElementById(‘video_’+settings.safeID) and get access to the methods which control the youtube player (play, pause etc).

youTubeEmbed-jquery-1.0.js – Part 3

var initialized = false;

// Creating a global event listening function for the video
// (required by YouTube's player API):

window['eventListener_'+settings.safeID] = function(status){

	var interval;

	if(status==-1)	// video is loaded
	{
		if(!initialized)
		{
			// Listen for a click on the control button:

			elements.control.click(function(){
				if(!elements.container.hasClass('playing')){

					// If the video is not currently playing, start it:

					elements.control.removeClass('play replay').addClass('pause');
					elements.container.addClass('playing');
					elements.player.playVideo();

					if(settings.progressBar){
						interval = window.setInterval(function(){
							elements.elapsed.width(
					((elements.player.getCurrentTime()/data.duration)*100)+'%'
							);
						},1000);
					}

				} else {

					// If the video is currently playing, pause it:

					elements.control.removeClass('pause').addClass('play');
					elements.container.removeClass('playing');
					elements.player.pauseVideo();

					if(settings.progressBar){
						window.clearInterval(interval);
					}
				}
			});

			initialized = true;
		}
		else{
			// This will happen if the user has clicked on the
			// YouTube logo and has been redirected to youtube.com

			if(elements.container.hasClass('playing'))
			{
				elements.control.click();
			}
		}
	}

In order to be able to control the video player, we need to be notified when certain events (like playback stopped, video ready etc) occur. Normally, this would mean that we need to pass a callback function, which is executed by the player every time such an event happens.

Unfortunately, flash can only execute functions if they are defined in the global scope and cannot see the functions which are defined inside the plugin. However, by creating functions with unique names (with the safeID) and explicitly adding them to the window object we can make this happen. If it weren’t for this little trick, it would be impossible for the plugin to work.

youTubeEmbed-jquery-1.0.js – Part 4

				if(status==0){ // video has ended
					elements.control.removeClass('pause').addClass('replay');
					elements.container.removeClass('playing');
				}
			}

			// This global function is called when the player is loaded.
			// It is shared by all the videos on the page:

			if(!window.onYouTubePlayerReady)
			{
				window.onYouTubePlayerReady = function(playerID){
					document.getElementById('video_'+playerID).addEventListener('onStateChange','eventListener_'+playerID);
				}
			}
		},'jsonp');

		return elements.originalDIV;
	}

})(jQuery);

The event listening function we created in the previous section of the code, is attached to the player with the addEventListener method. It is called every time when a “stateChange” occurs (playback start, playback pause, end of playback etc). A numeric code is passed to the event listening function as a parameter, corresponding to the event.

Now lets take a look at how our plugin is used.

script.js

$(document).ready(function(){

	$('#player').youTubeEmbed('http://www.youtube.com/watch?v=u1zgFlCw8Aw');

	/*
		//You can alternatively pass an object:

		$('#player').youTubeEmbed({
			video			: 'http://www.youtube.com/watch?v=u1zgFlCw8Aw',
			width			: 600, 		// Height is calculated automatically
			progressBar	: false		// Hide the progress bar
		});

	*/

});

You just need to call the youTubeEmbed() method and pass it either a string or a configuration object. If a string is passed, it is assumed to be the URL of a YouTube video. If you are passing an object make sure that you are passing the video property with a correct video URL.

Video Playing with a Progress Bar

Video Playing with a Progress Bar

Step 3 – CSS

Finally we are left with applying a few CSS styles to the player. They will change the design of the player controls and define the way they are positioned in the player window.

youTubeEmbed-jquery-1.0.css

.flashContainer{

	/*	Setting the container to relative positioning
		so we can center the control div */

	position:relative;
	overflow:hidden;
}

.progressBar{
	display:none;
	position:absolute;
	width:auto;
	height:8px;
	left:20px;
	right:105px;
	bottom:20px;
	background-color:#141414;
	overflow:hidden;
	cursor:pointer;

	/* A light CSS3 bottom highlight */

	-moz-box-shadow:0 1px 0 rgba(255, 255, 255, 0.3);
	-webkit-box-shadow:0 1px 0 rgba(255, 255, 255, 0.3);
	box-shadow:0 1px 0 rgba(255, 255, 255, 0.3);
}

.progressBar .elapsed{
	position:absolute;
	width:0;
	height:100%;
	background-color:#1fa2f6;
	border-right:1px solid #49AFF0;
}

.controlDiv{
	/* Centering the control div */
	position:absolute;
	width:120px;
	height:120px;
	cursor:pointer;
	top:50%;
	left:50%;
	margin:-60px 0 0 -60px;
}

.controlDiv.play{
	background:url('img/play.png') no-repeat center center;
}

.controlDiv.replay{
	background:url('img/replay.png') no-repeat center center;
}

.controlDiv.pause{
	background:url('img/pause.png') no-repeat -99999px;
}

.flashContainer:hover .controlDiv.pause{
	background-position:center center;
}

/* Only show the progress bar when the video is playing */

.flashContainer.playing:hover .progressBar{
	display:block;
}

To customize the look of the player you just need to change the color values above. Also you can edit the png files with the play/pause buttons. Clearly this is much easier than modifying the looks of the default youtube player. It also strips all of the unnecessary chrome and leaves you with what matters most – your video.

With this our Custom YouTube Player plugin is complete!

Did you like this tutorial? Share your thoughts in the comment section below.

Join our newsletter and get our PSDs!18,197 people learn about HTML5, JS and more. Join them!

by Martin Angelov

Martin is a web developer with an eye for design from Bulgaria. He founded Tutorialzine in 2009 and it still is his favorite side project.

88 Comments

  1. Kbdesign says:

    Superb! many thanks for this tutorial!

  2. Sahan says:

    Awesome !!

  3. Luigi says:

    Good thanks!!!

  4. Sandra says:

    Great post. Thanks for sharing.

    You could also first display youtube video images first and then swap them with the flash player. Browsers would be much snappier as well...

    Again, thanks for the post...

  5. jack says:

    awesome
    maybe u can add volume control and double click to full screen

    thanks

  6. Dave says:

    Question, not completely related, but ...

    Is is possible to automatically stop the video after X seconds?

    I see that you are using player.getCurrentTime and that returns the elapsed time in seconds since the video started playing.

    http://code.google.com/apis/youtube/js_api_reference.html

    Thanks.

    Dave

  7. Martin Angelov says:

    Thanks for the comments folks!

    @ Dave

    Not sure why you would want to do this, but it is possible. When play starts, you can set up a variable with the current time. Then, in the interval which updates the progress bar you can check how much time has the video been playing and if needed stop it by simulating a click on the control div.

    Here are a few code snippets that can get you started:

    // Setting up the time variable:
    
    var playStart = (new Date()).getTime();
    
    // Put this code in the youTubeEmbed-jquery-1.0.js – Part 3
    // inside the setInterval function:
    
    if (((new Date()).getTime() - playStart)/1000 > 30){
        // The video has been playing for 30 seconds
    
        elements.control.click(); // Simulating a click
    }
    
    
  8. Ondra H says:

    hi, nice plugin but maybe one other feature should be incorporated - redirection for smartphones without flash. Most of them have dedicated youtube apps that are activated by youtube link. Lot of people surf the web on their phones, actually im writing this on palm pre, and this would be nice for them. I use some jquery code to verify flash presence on my website (to replace embed player with video preview image & video host link) but maybe there is better technique to detect all those smartphone OS.

  9. Akihisa says:

    This is realley an awesome tutorial. :D

    Many thanks for this!

  10. Eliseu says:

    It would be nice if the progress bar gets less opaque when hover out, but not disappear.

  11. Great concept mate.

    two questions.

    1. could this be changed so that users could add a youtube vid on their profile pages. If so could you explain how.

    2. could we add a watermark for the player, with our site logo. That appears as overlay in different state options.

    a) all the time
    b) onload
    c) on hover

    Regards Ste

  12. Will Hancock says:

    Love it! Think I will be rolling this out across my sites!!

  13. incorporating the player just got a whole lot easier !

    http://www.tikku.com/jquery-youtube-tubeplayer-plugin

  14. DataQ Web says:

    Thanks for sharing this. I never used the YouTube API. Maybe I'll give it a try if I ever need to embed a video

  15. Awesome! Thanks so much for this.

  16. awesome. very very handy !

  17. greenbandit says:

    this plugin always embed lower quality video?

  18. Malli says:

    Awesome..

  19. Max Berndt says:

    Why got my comment deleted?
    Is this site getting censored?

    All I asked was:

    Why doesn't recognize this embedding method mobile devices not supporting FLASH and doesn't output HTML5 videos to them?

    The standard Youtube does it.

  20. kathy says:

    well i sorted out my problems from yesterday. but now that i have it ostensibly working i see that your play/pause buttons are just covering up the default youtube play graphic. how do i get rid of that?

  21. Ale says:

    cool as ever ;)
    this site is very good

  22. Rodrigo says:

    I wasn't able to unzip the download files for some reason and the custom video player doesn't work accordingly. I just took the files from demo, but the player doesn't work either. I have no idea.

  23. Rodrigo says:

    How can I auto play the video? Where do I have to put the lines?
    I've tried, but got no luck.

    Thanks!

  24. Martin Angelov says:

    @ kathy

    Unfortunately it isn't possible to get rid of it. According to a member of YouTube's development team, it is due to a bug in the chromeless player, which they are about the fix.

    But its been a couple of months and they've still not removed the play button, so the next best thing is to show the hqDefault thumbnail, available from the API response, over the video window ( you will need to offset it a bit if the video is widescreen ).

    @ Rodrigo

    The simplest way to autoplay the video is to trigger the click handler of the play button. You can do this by putting the following code after line 13 in youTubeEmbed-jquery-1.0.js – Part 4

    $('.controlDiv.play').eq(0).click();
    
  25. Rodrigo says:

    Martin,

    Thanks for your assistance! I tried your code accordingly, but no success for some reason. Basically when a page loads, the player should start automatically.

    Is there any other code? Thanks.

    Rodrigo

  26. Rodrigo says:

    Sorry, one more question. How to put volume level to 0 or even mute by default?

    Some people feel it bothering to see a page with sound. Thanks.

    Rodrigo

  27. Giannis says:

    Hi, one minor question. I did the whole setup, my videos are shown perfectly but..

    ..I have also the 2 videos at the end of mine videos!!

    The one with the bear and the other with the whale, the default videos.
    Still showing at the end of the others. Any help would be appreciated.

    Thanks for this script. It's awesome. Far away from the ugly embed look of youtube player.

  28. KillerKent says:

    @greenbandit

    If you want it to show Higher Quality you can use the 'cueVideoById' API call which has a 'suggested quality' parameter.

    I added this line:

    elements.player.cueVideoById(settings.videoID, 0, 'large')

    inside the 'onYouTubePlayerReady' block and that worked for us.

    Hope that helps.

    1. Vaibhav says:

      thanks it worked for me too.....

  29. Lament says:

    is it possible to hide/get rid of the YOUTUBE logo on the bottom of video screen?

  30. Martin Angelov says:

    @ Rodrigo

    There are probably better ways to do it, but I do not have the time to try it out. You can put the code i gave you in a setTimeout, So instead of:

    $('.controlDiv.play').eq(0).click();

    use this code:

    setTimeout(function(){$('.controlDiv.play').eq(0).click();},2500);

    As for your second question, I would probably want to take a look at the API documentation and try to implement the player.mute() method.

    @ Lament

    The YT logo is deeply embedded in their player. After all they are kind enough to provide all those great tools for free. If you still need to have the logo removed, I would suggest that you try out JW Player and host the video yourself as an flv file.

  31. Rodrigo says:

    Martin,

    The player now starts automatically! Looks great!

    Unfortunately, I'm not sure how to implement: player.mute():
    from google javascript api.

    I've looked at js files and tried, but no luck...

    Rodrigo

  32. knyttl says:

    Hello,

    the player is brilliant, there is just one minor thing – the player shows the "Play" button even before loading the flash player. If the button is pressed before the video is loaded, it does not start to play. It is quite confusing for those using the player first time.

    I would appreciate some help with this.

    Thanks!

  33. Rudy says:

    Is there a way to force the highest quality version of the video to play?

  34. Mike says:

    That makes a fine looking video player without all of the distracting stuff that the normal YouTube player provides. I would like to study up on this and learn how to add a volume control.

  35. Rodrigo says:

    I placed these codes accordingly.
    I 'm not sure for the answer in which Dave posted for limiting the video time.
    A short & quick help needed.

    // Setting up the time variable:

    var playStart = (new Date()).getTime();

    // Put this code in the youTubeEmbed-jquery-1.0.js – Part 3
    // inside the setInterval function:

    if (((new Date()).getTime() - playStart)/1000 > 30){
    // The video has been playing for 30 seconds

    elements.control.click(); // Simulating a click
    }

  36. Nooo.. but it dosent works with Internet Explorer.... i was modifying it in Firefox, and now thay i have finished i noticed that it dosent works in that bad explorator.. i hate ie!

    But good proyect, i was researching for more examples like this and i didnt find them, so excelent job. Thank You.

  37. Hello Martin,
    This is a great tutorial and a great introduction to the chromless player.

    Have you thought about doing a follow up tutorial, with some more advancements to this, that other people have suggested for example.

    * Mute/UnMute Toggle
    * Volume Slider - Using something like jQuery UI slider

    I have been thinking on how to do this, but unsure where to fit this in the player control, as it would be pretty crammed.

    Also is there way to detect a video will have adverts within it using the API, as playing around with some test videos the advert would sit ar the bottom of the player behind where the progress bar would be and is a bit distracting. If there is a way to detect maybe for example the progress bar could be positioned at the top depending on this case.

    Sorry for the 101 questions, but I am really keen for this technique to be progressed further, so that we have a good looking generic player.

    Look forward to your response.

    Thanks,
    Warren :)

  38. Hello Martain,
    Only me again. Just to let you know of a minor UI bug.

    To replicate do the following:
    * Let the YouTube video load in
    * Click on the video anywhere except YouTybe logo and the Play Button
    * The video starts to play however we still have the play button displayed

    Thought I would just let you know that. I am looking at this myself and if I fix it I will let you know.

    Thanks,
    Warren :)

    1. Irwin Nardo says:

      I noticed that same bug when running the page locally, however when I run it from my web server, the bug does not occur.

  39. Kenn says:

    Great! but the custom variables don't work in my case. It shows up the video of Youtube API team instead of my video.

  40. diego says:

    hi there, thnx for ths awesome code... hey I was trying to create a volume bar for this i guess im not that good coding... does anyone knows of a way to do this?

  41. Tim says:

    Sorry to open an old thread, but I wanted to add this section of code, starting at line 152 (at least in my file) and replacing the following appropriate lines...

    if ( settings.progressBar ) {
    interval = window.setInterval( function() {
    if ( typeof elements.player.getCurrentTime == 'function' ) {
    elements.elapsed.width(
    ( ( elements.player.getCurrentTime() / data.duration ) * 100 ) + '%'
    );
    } else {
    window.clearInterval(interval);
    }
    },1000);
    }

    I placed your code in a rotating set of images/videos that were swapped out, and without this you would get nasty console errors saying 'getCurrentTime is not a function' if you left the video before it was paused or had cleanly ended. There may be a more cohesive way of handling this, I just mimicked what you do in your pause function. Thanks for this code though, you made something great here.

  42. Guillaume says:

    Hello !

    Thanks for this great plugin, however, it seems not possible to go fullscreen with the javascript API, which is one of my requirements.

    Any thought about that ? Any workaround ?

    1. Martin Angelov says:

      Unfortunately it is not possible with the current API. I am also not sure if it is allowed at all - there might be a security restriction in flash to prevent this.

  43. dlaws says:

    I posted a comment a week or so ago but it doesnt seem to have been moderated. It'll try again, i want to be able to navigate through a list of videos using a previous/next button. Could you please advise? I thought i should be able to use the code below with an onlcick event button would do the trick but nothing seems to happen, any ideas or is it more complicated than this? Any help would be appreciated. Thank you for sharing your code.

    Dave

    function navVid(videoid){
    if(videoid == 1){
    $('##player').youTubeEmbed('http://www.youtube.com/watch?v=u1zgFlCw8Aw');
    } else if (videoid == 2){
    $('##player').youTubeEmbed('http://www.youtube.com/watch?v=u1zgFlCw8Aw');
    } else {
    $('##player').youTubeEmbed('http://www.youtube.com/watch?v=u1zgFlCw8Aw');
    }
    }

  44. This is a really awesome tutorial (like all your posts!)

    Implemented this technique here: http://www.hotelpepper.com/buzz.php

    Thanks for the tips : )

  45. Waiting for the volume implement sir, please add volume bar to it

  46. kathy says:

    when is youtube going to get rid of that HIDEOUS play button? i'm cool w/ keeping their brand in the bottom corner, but why bother w/ chromeless if you can't get rid of their ugly play button?

  47. Zac says:

    So, I have an interesting problem. Some of the videos I try to embed don't load. I've made sure that the YouTube video settings allow for the video to be embedded. I've also confirmed that my code (JavaScript) is working because it loads some videos without a problem. Here is a video I can't embed, for example.

    http://www.youtube.com/watch?v=dvP3glNgx4M

    This video is marked public and open for embedding and it also doesn't load.

    http://www.youtube.com/watch?v=-q4IN2XBLDU

    Thoughts?

  48. sadeesh says:

    First, thanks for providing this api...
    I used this code for autoplay... it works nice..
    setTimeout(function(){$('.controlDiv.play').eq(0).click();},2500);

    But, In firefox, its not working fine. And the whole script not loading properly. When i am trying to click the play button, it shown script error.

    Specifically more time in Firefox in Mac system

  49. jake says:

    Your demo

    http://demo.tutorialzine.com/2010/07/youtube-api-custom-player-jquery-css/youtube-player.html

    seems to no longer work as of Nov 16, 2011.

    Any idea why?

    1. strepsil says:

      Getting the same problem. Seems like the api demo isn't actually working either:

      http://code.google.com/apis/youtube/youtube_player_demo.html

      ..at the moment

    2. jake says:

      Nov 18, 2011. Now the demo is working again, same as it used to . And so is my implementation based on your code - Thanks for the tutorial.

      The strange 2 day outage affected all browsers, but not is healed. Lets hope this doesn't portend future problems from youtube.

  50. porchn says:

    http://demo.tutorialzine.com/2010/07/youtube-api-custom-player-jquery-css/youtube-player.html

    it error can't click to play button

  51. Staircase says:

    Player have error :(
    It was working yesterday fine - maybe google block some you tube api func?

  52. bStyler says:

    +1,
    the player does not work anymore for me also, would love to see any work around.

    Thanks!

  53. Matthew says:

    Yeah why isn't this working all of a sudden...

  54. slox says:

    Thanx for nice tutorial,,,

  55. digitalpbk says:

    Does youtube still support custom player?

  56. LB says:

    Works great... but still got troubles with urls with "-" before the video id e.g. http://www.youtube.com/watch?v=-lBaGgRTd7I

    Could anybody help? :)

  57. martijn black says:

    The play/stop buttons will not work with 'jquery-1.7.1.min.js', with the older version works fine.

    1. Dark says:

      It works, but seems not taken styles. I've tried to put in inline, and it works. But it is not the solution. Have you found it?

  58. 123 says:

    Current script gets information via search and not directly from video info page. If video id starts with special symbols like '-', youtube API does not return any results.
    To solve this issue, information has to be fetched directly from video information page:
    http://gdata.youtube.com/feeds/api/videos/VIDEO_ID?v=2&alt=jsonc
    instead of:
    http://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc&q=VIDEO_ID

    Updates in youTueEmbed-jquery-1.0.js:
    Line 47 changes to
    var youtubeAPI = 'http://gdata.youtube.com/feeds/api/videos/' + settings.videoID + '?v=2&alt=jsonc';
    Line 53 changes to
    if(response.error){

    1. Andrew says:

      If you take this approach you also need to remove the following line of code on like 61

      data = data.items[0];

      This line grabs the first result in the search results (#0) but since we are no longer doing a search and directly calling the specific video, having this line breaks the player.

  59. 123 says:

    To make it work with jQuery 1.7.1 all you need to do is just replace 'className' to 'class' in javascript file. :)

    1. LorenH says:

      Thanks 123! Here's a further tweak: For IE 7 and IE8 you can't use class as the key. You can, however, use "class".

      Wrap the 4 instances of 'class' in quotes. Example:

      elements.container = $('<div>',{"class":'flashContainer',css:{

    2. 456 says:

      Thanks that worked :)

  60. mark shirley says:

    Looks fantastic is there any tutorials that would show how to implement this into wordpress twentyeleven child theme

  61. Adam Frame says:

    Looks and works great for single videos. How do I make it work properly for playlists?

    I have added the Flashvar 'playlist' in the js and passed the list of video codes through the youTubeEmbed call and this works, but the play control reappears at the start of each video and the progress meter is not the correct length for the video currently playing.

    If you have any pointers on where I should be looking that would be great.

    Thanks.

  62. Sean says:

    This works fine, but with literally every youtube video I tested it on EXCEPT FOR MY OWN. I have no idea what setting my youtube account might have that is stopping me, the videos allow embedding and they're pubic. What small thing might I be overlooking??

  63. Justin says:

    Wonderful code! Beautiful! Thank you!!

  64. Raju Sharma says:

    Hello Martin ,

    I tried your demo code it is working but the player controls is not being displayed.

    And I want to be a favor from your side. The black bar appears in the YouTube video, it looks little odd when the video plays, Can we remove that black space from the videos ? I want to remove that black space and shows the video at desire aspect ratio as the we choose for the player size . For now I am using the stander google YT player API.

    Is it make any sense ?

    Thanks in advance , I am keen to get for valuable response....

    @Raju

  65. Amy says:

    Thanks for sharing your knowledge! I adapted your code and will be using it to add a curtain open/close effect for a trailer we have hosted with YouTube. The website is called Bass Cabaret. You can see a demo here: http://dev.amypospiech.com/custom-youtube-player/

    Best,
    Amy

  66. Will says:

    Bit behind the 8 ball - 12 months after the last comment.

    Does anyone have any suggestions for detecting, moving or completely removing the advertising placed by youtube/google?

    I will eventually be moving the controls to be outside the player if it comes to that.

    Thanks for any help

  67. Trent says:

    I tried to use this in order to add a custom play button graphic in place of Google's default play button. However it appears that this only overlays a graphic on top of the default YouTube play button so if my graphic is smaller, then I can still see the edges of the YouTube button below. Any suggestions for actually replacing the YouTube play button instead of just a positioned overlay?

  68. Dave says:

    Great tutorial!!!!

    Doesn't work for Unlisted videos so if anyone has figured that out please share!!

  69. Peter says:

    Great script. Clean and elegant. Thanks.

  70. najim says:

    wow!
    great tips. Thanks Martin

  71. Kantharaj says:

    Thanks Martin.

    How do I make it work properly for playlists?

  72. Shoaib says:

    Hi,
    its Awesome! Thanks so much for this and i am using that on my site and i integrate mute/unmute , volume slider , next and previous song all using jquery. but the player not working on IE, it show the blank screen, i have tried much thing but i unable to play a song on IE, please suggest.

    Waiting for Help :)

    Thanks

    1. Nick says:

      I know I'm late for this. I also suffered to this IE bug just a while ago.

      Here is the solution. In youTubeEmbed-jquery-1.0.js, at line 88 replace the value of wmode from "transparent" to "opaque". This will make the video visible in IE. :)

  73. igor felluga says:

    I sugget tu add &safeSearch=none to YouTube URL, sometimes you find a restricted video and js return an error

  74. fikiichsan says:

    why this script don't work in jquery 1.10.1? how to make this work?

  75. strepsil says:

    N.B. This does prevent users clicking the adverts.. which is probably against terms of use, and means they can't close them either..

Add Comment

Add a Reply

HTML is escaped automatically. Surround code blocks with <pre></pre> for readability.
Perks:   **bold**   __italics__   [some text](http://example.com) for links