jQuery: video trailer for YouTube

I've just created a demo that shows a nice implementation of a video trailer for our YouTube videos. My demo makes use of jQuery and jQuery UI effects to create a simple presentation of a video. The source code, in its essence, is made up of chained animations glued together by the callback functions of each animation. Feel free to use this demo in your own projects. Of course mentioning me would be surely appreciated. Enjoy!

jQuery: YouTube video slideshow

Creating a YouTube video slideshow with jQuery is exactly the same thing as creating any other jQuery slideshow. The only difference is that instead of divs or images we're dealing with the iframes used by YouTube to embed its videos in web documents. As you will see, there's nothing difficult with this. As usual, we start with our underlying markup first:

Embedding HTML5 videos from YouTube

Trying to embed a YouTube video using the HTML5 video element doesn't produce the desired result. The point is that the URL provided by YouTube to embed a video works only with the iframe element. Why so? Because you're actually fetching a Flash video on a page, not the actual file. Since browsers don't support Flash videos when included in an HTML5 video element, everything fails silently. This is due to the fact that browsers accept only a few video formats in HTML5, for example the Theora format or MP4 files. Flash videos are not included in their list. Another important thing to keep in mind is that the feature detection performed by YouTube in order to check whether your browser supports HTML5 videos seems to work only on YouTube and not remotely.

YouTube: changes to video embed code

Recently YouTube changed its HTML code to embed videos on your pages. Currently the object element has been replaced by an iframe element. This allows even more control over the final layout of the embedded video, though some inner controls are now delegated to the YouTube's engine itself. The good news is that now our markup is a lot cleaner and simpler, because we actually got rid of the annoying embed element contained in the object element. The final markup now looks like the following:

<iframe title="YouTube video player" class="youtube-player" type="text/html" width="640" height="390" src="http://www.youtube.com/embed/QVnRdCJLWX8" frameborder="0" allowFullScreen></iframe>

The most important changes are:

  • a class and title attribute attached to the iframe
  • the content type of the container element is now text/html
  • the URL of the src attribute is now in the form of http://www.youtube.com/embed/videoID, where videoID is the alphanumeric sequence contained at the end of a video's page URL (in this example is QVnRdCJLWX8
  • frameborder and allowFullScreen are not valid HTML attributes for this element, so you should bear this in mind when you want to pass the W3C validation.

jQuery: parsing a YouTube feed

Parsing a YouTube feed is very simple with jQuery. Since we're dealing with a remote resource, the first thing we need to do is to set up a server-side script that will fetch the feed for us. In this case we 're using the Most Viewed feed taken directly from the YouTube's home page (just follow the feed links that are linked from this page). However, there's a catch: this kind of feed mix up XML elements and HTML markup, so we need also to separate these two components. The server-side script, written in PHP, is the following:

header('Content-Type: text/html');
$youtube_rss = simplexml_load_file('http://gdata.youtube.com/feeds/base/standardfeeds/most_viewed?client=ytapi-youtube-index&time=today&v=2');

foreach($youtube_rss->entry as $entry) {


    echo '<div class="entry">' . $entry->content . '</div>' . "\n";


}

This script uses SimpleXML to fetch and parse the feed, returning a set of HTML elements containing the actual contents of the feed. Note that we're also serving our file as HTML. After this, the jQuery code is really straightforward to implement:

$(document).ready(function() {

    var htmlFeed = '';

    $.ajax({
    
    
        type: 'GET',
        url: 'youtube-feed.php',
        dataType: 'html',
        success: function(html) {
        
        
           htmlFeed = html;           
                      
           $(htmlFeed).appendTo('#youtube-feed');
        
        
        }
    
    
    
    
    });

We simply append the returned markup to our placeholder.

Demo

Live demo

jQuery: YouTube player plugin

jQuery YouTube Player is a powerful plugin that allows you to handle all the most common aspects related to YouTube's videos. In fact, with this plugin you can create video galleries, turn plain YouTube's textual links into working embedded videos and much more. The latter aspect is very important for accessibility reasons: by using a simple textual link in your markup you make sure that a fallback mechanism will be always available even when JavaScript is not supported or disabled. Further, with this plugin you can also extract metadata from YouTube, as shown below.

We are all in debt with the author of this plugin for his great work that surely will spare us a lot of time in the future. More info on github.

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>';
        
        
        $(video).appendTo(this);
        
        return this;
    };
})(jQuery);

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.

Example:

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

Demo

Live demo

Download

jquery.addYouTubeVideo.js

YouTube JavaScript Player API: coding problems

The YouTube JavaScript Player API allows developers to use JavaScript to load videos from YouTube and display several related options. The official API's guide is located on this page. At first glance, the documentation provided here seems reasonably complete and accurate and, to be honest, it is. Problems start when you try to implement something on your own. First, to make everything work, you need the SWFObject script that has to be included before any other script call, like so:

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>

Then you can use this object to run calls to the YouTube's API:

var params = { allowScriptAccess: "always" };
var atts = { id: "myytplayer" };
swfobject.embedSWF("http://www.youtube.com/v/8QRTkPrFbVQ?enablejsapi=1&playerapiid=ytplayer", 
                       "ytapiplayer", "425", "356", "8", null, null, params, atts);

The first part of this code is a params object literal with the various options that allow JavaScript to access the newly created HTML structure, which consists of an object element that, in turns, contains an embed element (to make it work in a cross-browser fashion). This object has an ID attribute that in this case is set to myytplayer and it's provided in the atts object literal. Everything is then passed to the embedSWF() method of the SWFObject library. The first parameter is an URL that contains the following data:

  1. The video's ID (here 8QRTkPrFbVQ), taken from the video's page URL
  2. enablejsapi=value for using JSONP
  3. the ID of the player

You can find more information on the other parameters here. You can also see a live demo here. Now let' start seeing what are the real problems with this API.

Calling object methods

Calling object methods should be simple. As the documentation says:

In order to call the player API methods, you must first get a reference to the player object you wish to control. This can be done by calling getElementById() on the object or embed tag containing the player SWF if using SWFObject to embed the player SWF.

Operations

If you call directly getElementById() on the referenced ID of your object element, you actually get a reference to a normal HTML element on the page, not to a member of the underlying JavaScript library. For example, if you try something like this:

var player = document.getElementById('myytplayer');
alert(player.getVideoEmbedCode());

you get an error, because you're still referencing to a normal HTML element. If we continue reading the documentation, we'll find a couple of examples that show how to make this work. The most important for our problem is this: http://code.google.com/apis/youtube/js_api_reference.html#GettingReference, where you learn how to get a reference of the object. But now an innocent coder will probably say: "Where I should put this function?". The documentation doesn't say anything about that. We still wonder: "How should we use this function?".

Code examples

The live example attached to the main documentation page should provide some code snippets to developers in order to better understand what's really going on behind the scenes. But there are no code snippets! Further, viewing the source code of the sample page won't help because the sources of the examples are not there. So we have only a couple of short snippets to work with. This is not of much help.

Conclusion

Lack of practical examples, details and usability cause in this case a lot of coding problems. The best thing you can do is to find on the web some good tutorial on the subject.