Embedding YouTube video in a web page is as easy as inserting few lines of YouTube embed code into the webpage. The embed code for each video is available on the YouTube website along with customization options. However it is often not desirable to store the whole embed code in your database. The embed code usually includes parameters such as width, height, border color and enable related videos. Assuring that these parameters are always the same for all videos stored in your application is sometimes difficult, specially if the embed code is submitted by people other than you.
Assuming that you have a list of YouTube video ids (e.g.
gzDS-Kfd5XQ) instead of the complete embed codes, it is relatively straight forward to present a consistent YouTube video interface in your application. Here is one way to do it:
- Include a reference to
swfobject.jsin the page. It is available under MIT License on the SWFObject home page. Alternatively you can link directly to this file. This example hotlinks to SWFObject version 2.
- Create an empty DIV tag that serves as a placeholder for the YouTube video player.
- Call the
swfobject.embedSWF()method with the appropriate parameters.
This code snippet generates output similar to that of a regular YouTube embed code but it is more customizable, consistent and easier to manage. The SWFLoader class also handles a few additional chores for you, such as flash player version detection. The generated YouTube video player has the following features:
- Related Videos are Disabled
- Full Screen Button is Enabled
For details about parameters not described in this example, see:
The next article demonstrates a variation of this code to display a list of YouTube videos and play them in a single player.