close menu

Adding YouTube Thumbnails to Your Web Page

June 2nd, 2009 by Gage Pacifera

Note: This post is one of a series of posts that breaks out the individual topics of my presentation “Pimp My Web Page” given at WebVisions 2009. You can see the fully pimped page that includes the code detailed below at http://pimpedblog.harmonicnw.com. Code tested for XHTML 1.0 Strict pages on IE 6 and 7 for PC, Firefox 3 for PC/mac, Safari 4 public beta for mac.

To add YouTube thumbnails to your web page, insert this code just above </body>:

<!-- youtube -->
<script type="text/javascript">
// <![CDATA[

	function showYouTubeThumbnails(data) {
		/** USER SETTINGS ***********/
		var highResThumbnails = false;			// set to false for normal (120px x 90px), set to true for high-resolution (320px x 240px)
		var targetId = "videos";					// Id of element where the thumbnails will be inserted
		/******************************/

		var feed = data.feed;
	 	var entries = feed.entry || [];
	 	var targetObj = document.getElementById(targetId);

	 	for (var i = 0; i < entries.length; i++) {
	    		var entry = entries[i];
	    		var link = entry['link'][0]['href'];
	    		var thumbnailUrl;
			var thumbnailWidth;
			var thumbnailHeight;
			var minimumHighResWidth = 320;	// minimum width for a high-resolution thumbnail

			var thumbnailsObj = entry['media$group']['media$thumbnail'];
			for (var j = 0; j < thumbnailsObj.length; j++) {
				thumbnailUrl = thumbnailsObj[j]['url'];
				thumbnailWidth = thumbnailsObj[j]['width'];
				thumbnailHeight = thumbnailsObj[j]['height'];
				if (thumbnailsObj[j]['width'] >= minimumHighResWidth && highResThumbnails || thumbnailsObj[j]['width'] < minimumHighResWidth && !highResThumbnails) {
					break;
				}
			}

	    		var newA = document.createElement('a');
	    		newA.href = link;
	    		newA.title = "YouTube video";

	    		var newImg = document.createElement('img');
	    		newImg.src = thumbnailUrl;
	    		newImg.width = thumbnailWidth;
	    		newImg.height = thumbnailHeight;
	    		newImg.alt = "YouTube video thumbnail";
			newA.appendChild(newImg);

	    		targetObj.appendChild(newA);
	  	}
	}

// ]]>
</script>
<script type="text/javascript" src="http://gdata.youtube.com/feeds/users/TheFreeBoxShow/uploads?alt=json-in-script&amp;format=5&amp;callback=showYouTubeThumbnails&amp;max-results=5"></script>
<!-- end youtube -->

In that second JavaScript block, replace TheFreeBoxShow with the YouTube username of your choosing and change the max-results=5 to the number of thumbnails you want.  You’ll also need to add this <div> where you want the thumbnails to appear:

<div id="videos"></div>

Background

This script uses a YouTube API to retrieve information on videos posted by a specific user. This method is public, so you don’t need to authenticate, and it can be done entirely in JavaScript. There are a lot of other cool things you can do with the YouTube API if you sign up for an authentication key, but this is a quick and easy way to pull down thumbnails without having to do that.

How It Works

That second block of JavaScript makes a request to the YouTube API and passes a few key parameters: YouTube username and number of results. In return, the YouTube API passes back a JSON object (basically just a JavaScript object) that contains a bunch of information that we’ll use. The function in the first block of Javascript code, showYouTubeThumbnails(), sifts through the object to find the bits of information we need and then writes them to the videos <div>. Note that the showYouTubeThumbnails() function was designated in the API request in the second block of JavaScript. Also note that the designated function must be declared before the API call.

I hand coded the showYouTubeThumbnails() function. Feel free to modify that function to make it do exactly what you want. You may want to peruse the documentation about the returned object.

Two Thumbnail Sizes

My parsing function allows you to use either high or low resolution thumbnails. The high resolution thumbnails are 320 pixels by 240 pixels, the low resolution thumbnails are 120 pixels by 90 pixels. You can choose which size thumbnail to use and also the id of the DOM object where the HTML is added by setting the appropriate variables in the first few lines of the function showYouTubeThumbnails():

  • highResThumbnails – If set to true, the function uses high resolution thumbnails. If set to false, it uses low resolution thumbnails
  • targetId – Id of the DOM object where the thumbnails will be added

Other Parameters

You’ll want to specify the username and the max-results parameters in the API call, but there are a few other optional parameters that you might find useful such as start-index, orderby and category. Go here for details on other parameters you can use.

The HTML Output

The new HTML created by showYouTubeThumbnails() will be structured like the example code below:

<a href="http://www.youtube.com/watch?v=GPH-c_3pXSc" title="YouTube video">
	<img width="120" height="90" src="http://i.ytimg.com/vi/GPH-c_3pXSc/2.jpg" alt="YouTube video thumbnail"/>
</a>
<a href="http://www.youtube.com/watch?v=tPFCq67LeLI" title="YouTube video">
	<img width="120" height="90" src="http://i.ytimg.com/vi/tPFCq67LeLI/2.jpg" alt="YouTube video thumbnail"/>
</a>
<a href="http://www.youtube.com/watch?v=SmpKajP1Veo" title="YouTube video">
	<img width="120" height="90" src="http://i.ytimg.com/vi/SmpKajP1Veo/2.jpg" alt="YouTube video thumbnail"/>
</a>

You can customize this HTML with CSS. For example, if you wanted to put a margin between the images you might add a stylesheet rule like #videos img { margin: 0 5px }.

Further Reading

Posted in HTML, JavaScript, Web Development, WebVisions

Back to blog home