May 22, 2009

Embed Multiple YouTube Videos in Your Web Applications

The JavaScript API enabled YouTube player demonstrated in the previous article supports additional interactivity through JavaScript. The following code snippet allows you to dynamically load a YouTube video in the player. Assuming that you have a database containing YouTube video ids, this example can be used to render a playlist of videos along with the YouTube player.

JavaScript/HTML Code and Demo

Notes

This code samples includes a ytplayer_loadvideo() function which encapsulates the loadVideoById() function available in the YouTube JavaScript API. You can substitute it with an alternative function cueVideoById() which prepares the player for the specified video but does not play it automatically. Details about these and other functions are available at YouTube JavaScript Player API Reference.

Bonus Tip: Fetching YouTube Video Thumbnails

Though not officially documented, you can use this little trick to fetch a static thumbnail of a YouTube video by requesting an image from these URLs:

  • http://img.youtube.com/vi/INSERT_YOUTUBE_VIDEO_ID_HERE/default.jpg (recommended)
  • http://img.youtube.com/vi/INSERT_YOUTUBE_VIDEO_ID_HERE/hqdefault.jpg (larger thumbnail)
  • http://img.youtube.com/vi/INSERT_YOUTUBE_VIDEO_ID_HERE/mqdefault.jpg
  • http://img.youtube.com/vi/INSERT_YOUTUBE_VIDEO_ID_HERE/1.jpg
  • http://img.youtube.com/vi/INSERT_YOUTUBE_VIDEO_ID_HERE/2.jpg
  • http://img.youtube.com/vi/INSERT_YOUTUBE_VIDEO_ID_HERE/3.jpg