<<< 25 years ago

Home

Sunday, January 25, 2009 01:05 PM >>>


embedding YouTubes

Sunday,  01/25/09  11:32 AM

<nerdy optional=completely>

In the public interest (and so I can find it later), I thought I'd reveal how I embed YouTube videos.  YouTube makes this really easy, and they take you almost all the way there, but not quite quite.

If you view a video on the YouTube site, you'll notice at the upper right they have an Embed text box with the HTML you have to insert in a page to play that video.  You can configure the size, whether to include a border, the color, and so on...  really nice.  But just sticking this HTML into your page this isn't exactly what you want, because what you really want is to display an image first which, when clicked, causes the YouTube video to play.  This is prettier for people who visit the page itself, and much prettier for people who read the page via RSS readers and so on which may not know what to do with embedded videos.

Okay, so how is this done?  Well first make the image; generally edited from a screenshot of the YouTube video, but it can be any image at all.  And then insert the following HTML into the page:

  1. <center>
  2. <img id="ytimg"  src="img_url.jpg" style="cursor: pointer"
  3.     onclick='ytimg.style.display="none"; ytvid.style.display="inline"'>
  4. <div id="ytvid" style="display: none">
  5. <object width="640" height="505">
  6. <param name="movie"
  7.     value="http://www.youtube.com/v/G0FtgZNOD44&hl=en&fs =1&autoplay=1" />
  8. <param name="allowFullScreen" value="true" />
  9. <param name="allowscriptaccess" value="always" />
  10. <embed src="http://www.youtube.com/v/G0FtgZNOD44&hl=en&fs=1&autoplay=1"
  11.     type="app lication/x-shockwave-flash"
  12.     allowscriptaccess="always" allowfullscreen="true"
  13.     width="640" height="505" />
  14. </object>
  15. </div>
  16. </center>

The numbers are so I can refer to the lines.  The brown text is what you get from YouTube's Embed text string.  You start by copying that in, and then add the rest.  Some notes:

Line 1/16 are optional if you want to center the whole thing.
Line 2 includes the image; the src= parameter gives the image URL.  Note pointing hand cursor.
Line 3 is what happens when you click; the image is hidden and the video is displayed.
Line 4/15 are a <div> surrounding the video; this is what you enable.
Line 7 and 10 add &autoplay=1 to the video URLs so the video plays immediately.

One more note: for more than one of these on a page, use unique id= values for the <img> and <div> tags, and modify the onlick= JavaScript accordingly...

</nerdy>