jQuery Youtube Player Plugin

I needed some code to show a youtube video in an overlay on my teapot page.

So I’ve found this easy to use jQuery plugin: jQuery Youtube Player Plugin.

Almost everything I needed was already implemented, I just had to add the functionality to start from a certain time.

Oh also, while I was changing stuff, I fixed a css issue with the rounded corners it didn’t look right because of the youtube video.
Just add this somewhere in your stylesheet:

div.youtubepopup div.ui-corner-all {
    border-radius: 6px 6px 0 0;
}

And I changed the default attribute for the youtube Id to data-youtube-id because the rel attribute is supposed to specify the relationship between the current document and the linked document, not some unrelated data…
Because of this attribute we don’t need to use a class to select our youtube links we can simple use:

$(document).ready(function() {
	$("a[data-youtube-id]").YouTubePopup();
});

You can get the complete code after the jump!

/*!
 * jQuery YouTube Popup Player Plugin v2.1
 * http://lab.abhinayrathore.com/jquery_youtube/
 * Last Updated: May 23 2012
 * Added HTML5 data attribute stuff and the start-from option - qwaxys
 */
(function ($) {
	var YouTubeDialog = null;
	var methods = {
		//initialize plugin
		init: function (options) {
			options = $.extend({}, $.fn.YouTubePopup.defaults, options);

			// initialize YouTube Player Dialog
			if (YouTubeDialog == null) {
				YouTubeDialog = $('<div></div>').css({ display: 'none', padding: 0 });
				$('body').append(YouTubeDialog);
				YouTubeDialog.dialog({ autoOpen: false, resizable: false, draggable: options.draggable, modal: options.modal,
					close: function () {
						YouTubeDialog.html(''); 
						$(".ui-dialog-titlebar").show();
					}
				});
			}

			return this.each(function () {
				var obj = $(this);
				var data = obj.data('YouTube');
				if (!data) { //check if event is already assigned
					obj.data('YouTube', { target: obj, 'active': true });
					$(obj).bind('click.YouTubePopup', function (event) {
						var youtubeId = options.youtubeId;
						if ($.trim(youtubeId) == '') youtubeId = obj.attr(options.idAttribute);
						var videoTitle = $.trim(options.title);
						if (videoTitle == '') {
							if (options.useYouTubeTitle) setYouTubeTitle(youtubeId);
							else videoTitle = obj.attr('title');
						}
						var youtubeStart = 0;
						if (obj.attr(options.startAttribute) !== undefined) {
							youtubeStart = obj.attr(options.startAttribute);
						}

						//Format YouTube URL
						var YouTubeURL = "http://www.youtube.com/embed/" + youtubeId + "?rel=0&showsearch=0&autohide=" + options.autohide;
						YouTubeURL += "&autoplay=" + options.autoplay + "&color1=" + options.color1 + "&color2=" + options.color2;
						YouTubeURL += "&controls=" + options.controls + "&fs=" + options.fullscreen + "&loop=" + options.loop;
						YouTubeURL += "&hd=" + options.hd + "&showinfo=" + options.showinfo + "&color=" + options.color + "&theme=" + options.theme;
						YouTubeURL += "&start=" + youtubeStart;

						//Setup YouTube Dialog
						YouTubeDialog.html(getYouTubePlayer(YouTubeURL, options.width, options.height));
						YouTubeDialog.dialog({ 'width': 'auto', 'height': 'auto' }); //reset width and height
						YouTubeDialog.dialog({ 'minWidth': options.width, 'minHeight': options.height, title: videoTitle, dialogClass: 'youtubepopup'});
						YouTubeDialog.dialog('open');
						$(".ui-widget-overlay").fadeTo('fast', options.overlayOpacity); //set Overlay opacity
						if(options.hideTitleBar && options.modal){ //hide Title Bar (only if Modal is enabled)
							$(".ui-dialog-titlebar").hide(); //hide Title Bar
							$(".ui-widget-overlay").click(function () { YouTubeDialog.dialog("close"); }); //automatically assign Click event to overlay
						}
						if(options.clickOutsideClose && options.modal){ //assign clickOutsideClose event only if Modal option is enabled
							$(".ui-widget-overlay").click(function () { YouTubeDialog.dialog("close"); }); //assign Click event to overlay
						}
						event.preventDefault();//this is better!
					});
				}
			});
		},
		destroy: function () {
			return this.each(function () {
				$(this).unbind(".YouTubePopup");
				$(this).removeData('YouTube');
			});
		}
	};

    function getYouTubePlayer(URL, width, height) {
        var YouTubePlayer = '<ifr'+'ame title="YouTube video player" style="margin:0; padding:0;" width="' + width + '" ';
        YouTubePlayer += 'height="' + height + '" src="' + URL + '" frameborder="0" allowfullscreen></ifr'+'ame>';
        return YouTubePlayer;
    }
	
	function setYouTubeTitle(id) {
		var url = "https://gdata.youtube.com/feeds/api/videos/" + id + "?v=2&alt=json";
		$.ajax({ url: url, dataType: 'jsonp', cache: true, success: function(data){ YouTubeDialog.dialog({ title: data.entry.title.$t }); } });
	}

	$.fn.YouTubePopup = function (method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist on jQuery.YouTubePopup');
		}
	};

	//default configuration
	$.fn.YouTubePopup.defaults = {
		'youtubeId': '',
		'title': '',
		'useYouTubeTitle': true,
		'idAttribute': 'data-youtube-id',
		'startAttribute': 'data-youtube-start',
		'draggable': false,
		'modal': true,
		'width': 640,
		'height': 480,
		'hideTitleBar': false,
		'clickOutsideClose': false,
		'overlayOpacity': 0.5,
		'autohide': 2,
		'autoplay': 1,
		'color': 'red',
		'color1': 'FFFFFF',
		'color2': 'FFFFFF',
		'controls': 1,
		'fullscreen': 1,
		'loop': 0,
		'hd': 1,
		'showinfo': 0,
		'theme': 'light'
	};
})(jQuery);

PS: on line 78 and 79 you can remove the accents and plus sign, that’s just because wordpress doesn’t allow me to write the full iframe tag😛


2 Comments on “jQuery Youtube Player Plugin”

  1. Bramus! says:

    Why not push this code onto GitHub?😉


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s