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:
http://www.youtube.com/watch?v=_AJ0SkbPxAk
http://www.youtube.com/watch?v=EuAVgWJ28Hw&feature=related

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');
      divbg.style.visibility = "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";
      divobj.style.visibility = "visible";
      var divWidth = width + 4;
      var divHeight = height + 20;
      divobj.style.width = divWidth + "px";
      divobj.style.height = divHeight + "px";
      var divLeft = (pageWidth - divWidth) / 2;
      var divTop = (pageHeight - divHeight) / 2 - 10;
      //Set Left and top coordinates for the div tag
      divobj.style.left = divLeft + "px";
      divobj.style.top = divTop + "px";
     
      //Create dynamic Close Button Div
      var closebutton = document.createElement('div');
      closebutton.style.visibility = "visible";
      closebutton.innerHTML = "<span onclick=\"closeYouTube('" + id +"')\" class=\"close_button\">X</span>";
      //Add Close Button Div to YouTube Popup Div container
      divobj.appendChild(closebutton);

      //Create dynamic YouTube Div
      var ytobj = document.createElement('div');
      ytobj.setAttribute('id', "yt" + id);
      ytobj.className = "ytcontainer";
      ytobj.style.width = width + "px";
      ytobj.style.height = 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 = "http://www.youtube.com/v/" + 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
      divobj.appendChild(ytobj);
     
      //Add YouTube Popup Div container to HTML BODY
      document.body.appendChild(divobj);
}
function closeYouTube(id){
      var divbg = document.getElementById('bg');
      divbg.style.visibility = "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
}
</script>

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; }
-->
</style>

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.

36 comments:

  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.

    http://img513.imageshack.us/i/39312839.jpg/

    ReplyDelete
  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.

    ReplyDelete
  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.

    http://xrl.in/73px

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

    ReplyDelete
    Replies
    1. Hi,

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

      Thanks

      Delete
    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

      Delete
  4. hello, can you test this code: http://xrl.in/73yk 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: http://xrl.in/73y9

    ReplyDelete
  5. ok I solved it thanks anyway

    ReplyDelete
  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?

    ReplyDelete
  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:
    divobj.style.top = Math.abs(divTop + Y) + "px";

    ReplyDelete
    Replies
    1. Where does this line go?

      divobj.style.top = Math.abs(divTop + Y) + "px";

      Delete
    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

      Delete
    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.

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

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

    ReplyDelete
  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?

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

    Thx.

    ReplyDelete
  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!!!!!

    ReplyDelete
  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.

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

    ReplyDelete
  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 - cristopher@nettechno.com

    Please Suggest me something.

    Thanks
    Cristopher.

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

    Regards

    Felix

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

    Jason.

    ReplyDelete
  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.

    ReplyDelete
  19. The Close button does not seem to work.

    ReplyDelete
  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.

    Thanks

    ReplyDelete
  21. http://www.khmerleadership.org/p/khmer-video.html

    ReplyDelete
  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

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

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

    ReplyDelete
  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

    ReplyDelete
  26. wow super got what i was googling on internet

    ReplyDelete
  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

    ReplyDelete

Thanks a lot for your valuable comments :)