jQuery: add a video from YouTube

Have you ever tried to insert the "Embed" code of a YouTube's video on your page and then validate it? Actually, the resulting markup is not valid, because the object element lacks of some required attributes. Of course you can't modify your markup without affecting the global embedded code. And this is where jQuery comes to the rescue. In fact, we can create a jQuery plugin that inserts the embedded code without invalidating our pages. I've created a simple, very simple plugin called addYouTubeVideo() whose code is as follows:

(function($) {
    $.fn.addYouTubeVideo = function(options) {
        options = options || {};
        options.width = options.width || '425';
        options.height = options.height || '344';
        options.url = options.url || '';
        var video = '<object width="' + options.width + '" height="' + options.height + '"><param name="movie" value="' +
        options.url + '"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="' + options.url + '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="' + options.width + '" height="' + options.height + '"></embed></object>';
        return this;

Its options are:

addYouTubeVideo() options
Option Value
width String. The width of the video.
height String. The height of the video.
url String. The URL of the video provided in your "Embed" code.


$(document).ready(function() {
   $('#test').addYouTubeVideo({width: '500', height: '440', url:'http://www.youtube.com/v/Nb_Rch9wmmw?fs=1&hl=en_US'}); 


Live demo



Leave a Reply

Note: Only a member of this blog may post a comment.