Friday, June 5, 2009

Easy to use Popup YouTube Player using JavaScript and DHTML

UPDATE: Please use the latest jQuery plugin: jQuery YouTube Popup Player Plugin

YouTube provides a very neat customizable player to embed on your web pages, but not always you want most of your page area consumed by YouTube Video windows. So for that reason I have created an easy to use YouTube Popup window which can be embedded dynamically into the page just by clicking a link.

Using the popup div tag concept from my previous post, I have modified it to create dynamic div tags using JavaScript which makes it easier to embed multiple videos on the page without creating static div containers for the videos. To embed a video you just need to create any kind of image or text link which calls the JavaScript openYouTube() function on mouse click to create dynamic popup window. The link should appear something like this:

<a href="#" onclick="openYouTube('video_id')">Video Title</a>

Where video_id can be extracted from YouTube URL’s as shown in red below:

Video Id consists of all the characters between “v=” and “&” (if any).

Advantages of using this popup YouTube player:

  1. Zero coding required!!!
  2. Piece of cake to embed YouTube popup windows by just calling the openYouTube() function from any link/button.
  3. Easily customizable YouTube parameters in the JavaScript function.
  4. No static Div tags required for each YouTube link.

This is how the Popup YouTube player looks like:Popup YouTube Player

The openYouTube() function contains customizable YouTube parameters like video width & height, full screen control, auto play control and high definition playback control. You can modify this function and pass all these YouTube parameters as function parameters in openYouTube() which will give you individual control over all the videos on a single page.

UPDATE: Please use the latest jQuery plugin: jQuery YouTube Popup Player Plugin

Popup YouTube Player JavaScript code:
<script language="javascript">
function openYouTube(id){
      //YouTube Player Parameters
      var width = 640;
      var height = 505;
      var FullScreen = "yes";
      var AutoPlay = "yes";
      var HighDef = "yes";
      //Calculate Page width and height
      var pageWidth = window.innerWidth;
      var pageHeight = window.innerHeight;
      if (typeof pageWidth != "number"){
      if (document.compatMode == "CSS1Compat"){
            pageWidth = document.documentElement.clientWidth;
            pageHeight = document.documentElement.clientHeight;
      } else {
            pageWidth = document.body.clientWidth;
            pageHeight = document.body.clientHeight;
      // Make Background visible...
      var divbg = document.getElementById('bg'); = "visible";
      //Create dynamic Div container for YouTube Popup Div
      var divobj = document.createElement('div');
      divobj.setAttribute('id',id); // Set id to YouTube id
      divobj.className = "popup"; = "visible";
      var divWidth = width + 4;
      var divHeight = height + 20; = divWidth + "px"; = divHeight + "px";
      var divLeft = (pageWidth - divWidth) / 2;
      var divTop = (pageHeight - divHeight) / 2 - 10;
      //Set Left and top coordinates for the div tag = divLeft + "px"; = divTop + "px";
      //Create dynamic Close Button Div
      var closebutton = document.createElement('div'); = "visible";
      closebutton.innerHTML = "<span onclick=\"closeYouTube('" + id +"')\" class=\"close_button\">X</span>";
      //Add Close Button Div to YouTube Popup Div container

      //Create dynamic YouTube Div
      var ytobj = document.createElement('div');
      ytobj.setAttribute('id', "yt" + id);
      ytobj.className = "ytcontainer"; = width + "px"; = height + "px";
      if (FullScreen == "yes") FullScreen="&fs=1"; else FullScreen="&fs=0";
      if (AutoPlay == "yes") AutoPlay="&autoplay=1"; else AutoPlay="&autoplay=0";
      if (HighDef == "yes") HighDef="&hd=1"; else HighDef="&hd=0";
      var URL = "" + id + "&hl=en&rel=0&showsearch=0" + FullScreen + AutoPlay + HighDef;
      var YouTube = "<object width=\"" + width + "\" height=\"" + height + "\">";
      YouTube += "<param name=\"movie\" value=\"" + URL + "\"></param>";
      YouTube += "<param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param>";
      YouTube += "<embed src=\"" + URL + "\" type=\"application/x-shockwave-flash\" ";
      YouTube += "allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"" + width + "\" height=\"" + height + "\"></embed></object>";
      ytobj.innerHTML = YouTube;
      //Add YouTube Div to YouTube Popup Div container
      //Add YouTube Popup Div container to HTML BODY
function closeYouTube(id){
      var divbg = document.getElementById('bg'); = "hidden";
      var divobj = document.getElementById(id);
      var ytobj = document.getElementById("yt" + id);
      divobj.removeChild(ytobj); //remove YouTube Div
      document.body.removeChild(divobj); // remove Popup Div

Popup YouTube Div CSS code:
<style type="text/css">
.popup {
      position: absolute;
      z-index: 2;
.popup_bg {
      position: absolute;     visibility: hidden;
      height: 100%; width: 100%;
      filter: alpha(opacity=70); /* for IE */
      opacity: 0.7; /* CSS3 standard */
      left: 0px; top: 0px;
      background-color: #999;
      z-index: 1;
.ytcontainer {
      border: 2px solid #666;
      clear: both;
.close_button {
      font-family: Verdana, Geneva, sans-serif;
      font-size: small; font-weight: bold;
      color: #666; text-decoration: none;
      display: block; float: right;
      background-color: #FFF;
      z-index: 3; cursor: default;
      border: 2px solid #666;
      margin-bottom: -2px;
      padding: 0px 3px 0px 3px;
body { margin: 0px; }

HTML code to embed YouTube Popup windows:
<a href="#" onclick="openYouTube('_AJ0SkbPxAk')">Stewie Beats Brian</a><br />
<a href="#" onclick="openYouTube('EuAVgWJ28Hw')">Stewie Beats Brian Part-2</a><br />
<a href="#" onclick="openYouTube('aRn5-LQCg2s')">Family Guy - Puke-A-Thon</a><br />
<a href="#" onclick="openYouTube('5IQ9mpFZz9c')">Family Guy - Electric Man</a><br />
<div id="bg" class="popup_bg"></div>

You can put the CSS and JavaScript code in separate .CSS and .JS files to keep your HTML code neat and clean.


  1. thanks for this fantastic script, but I tried to use it on my blog and it works great with all browsers except with google chrome. I attach a picture to make you understand the problem, and if maybe you can tell me a solution. I await your response.

    1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai

  2. fask, sorry I could not reply to you soon enough. I was keeping busy with something else.
    So, I tried this player in my Chrome and it works just fine on my side.
    Use Firebug in Firefox to diagnose the problem. From the screen-shot its looks like that everything is loading fine but the video is not playing. You can look for any other tags which might interfere with the css layout for this player.
    I am sorry, you'll have to debug it on your side as I am not able to replicate the problem on my side.
    Use Firebug in Firefox or Dragonfly in Opera.

  3. ok the problem with google chrome has been fixed, now I want to ask for help do the same thing with the player cacaoweb.

    Here you can find an open thread on the subject. Can you give me a hand?

    1. Hi,

      Video is not working for me in Chrome. Could you please assist me.


    2. Hi I think your problem is 'Blocked loading mixed active content' you can try to change url for youtube video from http to https

  4. hello, can you test this code: now I can open the player cacaoweb but I can not let him pass the ID, it gives me invalid URL link. this is the test page:

  5. ok I solved it thanks anyway

  6. Thanks for the script!
    I have put a couple of videos in ul list vertically. How can I play each video from where it is clicked instead of jumping back to the top and starting to play?

  7. Xeme,
    Here is something you'll have to add to your code to adjust the Y-offset for the player.

    Add this function to get the page Y-offset:
    function Y_offset() {
    return window.pageYOffset ? window.pageYOffset : document[(document.compatMode == 'CSS1Compat') ? 'documentElement' : 'body'].scrollTop;

    Then get this offset in the openYouTube() function:
    var Y = Y_offset();

    Then add this "Y" to this line in the code: = Math.abs(divTop + Y) + "px";

    1. Where does this line go? = Math.abs(divTop + Y) + "px";

    2. Please i am new to css,java popup. i am having problem with the popup. My problem is, i have a lot of videos on my site,when i click on any video at the bottom of the page, it plays right at the top of the page. Is it not possible for it to play at the same spot ? please i am waiting for your reply. Thanks

    3. OK how do you now prevent the page from scrolling? The above code puts the pop up in the correct place but the page still scrolls to the top.

      Nice script by the way. Thanks for doing it.

  8. hello Abhinay, You can do the same thing with Megavideo? I can give an example? thanks

  9. hey man. please respond to my question. can i change this code that my youtube video could start onload? or something like that...

  10. thanks for the code it works awesome! after I exit the popup window displaying the youtube video my title changes to #. does anyone know how i correct this?

  11. @day_trader - just add "; return false;" to link ;)
    Great example and great base for making the same stuff with other videos and stuff.


  12. Thanks for the reply, Abhinay Rathore also gave me this fix:

    Try using href="javascript:void(0)" instead of href="#" in your link.

    Thanks again for the help!!!!!

  13. This is very easy to use script. I used the fix to make the DHTM window open on clicked place. But the small problem is still the background of DHTML window still visible on top, not in the place DHTML window opening. Hope you will give a fix for that too. Thanks.

  14. Everyone,
    Please use the latest jQuery plugin for better browser compatibility and efficiency: jQuery YouTube Popup Player Plugin

  15. hello , I used your code and it works fine in all the browsers. So first of all thank you very much for this.

    Now one problem is that after the video is completed it should be closed automatically.

    How can I achieve this functionality?
    My Email -

    Please Suggest me something.


  16. How can I integrate the code in Net Objects Fusion Essentials?
    Thank you very much in advance!



  17. This Rocks! Thank you so very much, it worked like a charm.


  18. Great, the demo page really helped. Is there a way I can change the font on the toolbar? The different themes only change the color scheme.

  19. The Close button does not seem to work.

  20. Does anyone have any tips for using this code in Adobe RoboHelp? I am vary unfamiliar with the program and would like to know if I can insert the code.



  22. This is very interesting, You are a very skilled blogger. I’ve joined your rss feed and look forward to seeking more of your wonderful post. Also, I’ve shared your website in my social networks!
    website design

  23. GREAT!!!!!
    THANKS A LOT!!!!!

  24. Hi, i am new to jquery, your code works fine, but help me to have playlists with this videos

  25. That's very good... i think this information really help me...
    Very Useful information... awesome description and easy steps... Keep sharing more!!!
    Visit:- Youtube Help

  26. wow super got what i was googling on internet

  27. Hi Abhinay,

    Can I use this plugin for other videos like Youku videos (China has youtube instead of youku) by Changing the URL and writing code to get the youku video id. Because the same popup implementation is required for Youku videos too. Can you please suggest on this? It would be really helpful

  28. Guaranteed #1 Search Engine Ranking Supreme Free Viral Traffic Join Now Get Millions Of Hits Free To Your Site/Blog!

    PornKings Adult Shopping Backlinks-Shopping Mega Store Legendary Stars As Stormy Daniels,Shawna Edwards,Jenna Jamison-New Adult Stars Movies,Adult Toys,Enhancers,Merchandise-More !

    Hits Express Rotator System Do You Need Visitors to Your Website or Affiliate Program? If your looking to gain more visitors to your website Hits Express is your answer. With our program your site is being shown to people all over the world 24/7 365 days a year!

    PAYDIR Free For All Forum Portal Search Engine Crawled Network PR10 Ranking Information Forum XXX!

    FreeLinkExchanges Be Seen In 12 Nations 312 Sites Over 30 Millions Viewers Monthly Buy Featured Link Now With 150 Search Engines Crawling The Network!

    How do I get guaranteed traffic? When someone signs up from your site, they must first click on your classified ad which will open a new window leading to your main website. They will have to wait a few seconds for the code to appear on a separate frame at the top of the screen reach millions free now!

    Blast Your Ad to Over 23,000 Opt-in Prospects at ShowMyLinks Submit Your Solo Email Ad to All Showmylinks Members GET YOUR TEXT LINK ADs LISTED 100% FREE FOR LIFE PLUS EARN MONEY TO YOUR PAYPAL!!

    Adult Store Empires Backlinks Resources Search Engine XXX!

    GET YOUR OWN MONEY-MAKING AD BOARD -- Integrating Text ad, Banner Ad and Email Ad into one Portal Make Money Fast With Your Paypal Reach Million Dollars In A Year Fast !

    Full Length Homemade Videos Watch real people's private home sex videos. Forget about those shitty 1-2 minute clips, these are all high quality full length videos! 40+ Bonus Sites You will also get full access to the entire reelpass network of sites which features over 40+ awesome movie sites, 1000's of movies and pictures to download! Download, Burn & Share Not only do you get to watch all our movies, you can also download every single one and save it forever, burn them to dvd or share with friends!!

  29. Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site.
    python Training institute in Pune
    python Training institute in Chennai
    python Training institute in Bangalore


Thanks a lot for your valuable comments :)