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.

Thursday, June 4, 2009

Popup Div tag with close button using JavaScript and DHTML

Popup Div tag’s are very common on websites these days. Popup div tags can be used to display some vital information or focus on some particular content rather then whole page. I have created a very easy to use DHTML & JavaScript code for popup div tag with close button and a transparent page background which disables any clicks on the parent window.

I have implemented this script in such a manner that you can put any number of popup div tags on a single page with different id’s. The close button for every popped up Div tag is automatically generated by the script.

The Trick: CSS has a property named visibility which can be used to display or hide any entity to which it is applied. These popup div tags can be placed anywhere in the HTML code, and when the popup link/button is clicked, the popup div tag’s visibility is set to visible (initially hidden) and it is aligned at center of the page by using my previous JavaScript for center aligning a div tag at page center. I have also used a transparent background div tag which covers the remaining background and disables clicking on the parent window. There is only one transparent background for every page and it is layered below the popup div tags using the z-index property of CSS.

Popup Div Tag with close button

There are 2 JavaScript functions used here, one to open the div tag and align it to page center and the second function is to hide the popup and background div tags.

Popup Div JavaScript Code:
<script language="javascript">
function openpopup(id){
      //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 the background div tag visible...

      var divbg = document.getElementById('bg');
      divbg.style.visibility = "visible";
       
      var divobj = document.getElementById(id);
      divobj.style.visibility = "visible";
      if (navigator.appName=="Microsoft Internet Explorer")
      computedStyle = divobj.currentStyle;
      else computedStyle = document.defaultView.getComputedStyle(divobj, null);
      //Get Div width and height from StyleSheet
      var divWidth = computedStyle.width.replace('px', '');
      var divHeight = computedStyle.height.replace('px', '');
      var divLeft = (pageWidth - divWidth) / 2;
      var divTop = (pageHeight - divHeight) / 2;
      //Set Left and top coordinates for the div tag
      divobj.style.left = divLeft + "px";
      divobj.style.top = divTop + "px";
      //Put a Close button for closing the popped up Div tag
      if(divobj.innerHTML.indexOf("closepopup('" + id +"')") < 0 )
      divobj.innerHTML = "<a href=\"#\" onclick=\"closepopup('" + id +"')\"><span class=\"close_button\">X</span></a>" + divobj.innerHTML;
}
function closepopup(id){
      var divbg = document.getElementById('bg');
      divbg.style.visibility = "hidden";
      var divobj = document.getElementById(id);
      divobj.style.visibility = "hidden";
}
</script>

CSS Code for the Popup Div tag, Close Button and Background Div tag:
<style type="text/css">
<!--
.popup {
      background-color: #DDD;
      height: 300px; width: 500px;
      border: 5px solid #666;
      position: absolute; visibility: hidden;
      font-family: Verdana, Geneva, sans-serif;
      font-size: small; text-align: justify;
      padding: 5px; overflow: auto;
      z-index: 2;
}
.popup_bg {
      position: absolute;
      visibility: hidden;
      height: 100%; width: 100%;
      left: 0px; top: 0px;
      filter: alpha(opacity=70); /* for IE */
      opacity: 0.7; /* CSS3 standard */
      background-color: #999;
      z-index: 1;
}
.close_button {
      font-family: Verdana, Geneva, sans-serif;
      font-size: small; font-weight: bold;
      float: right; color: #666;
      display: block; text-decoration: none;
      border: 2px solid #666;
      padding: 0px 3px 0px 3px;
}
body { margin: 0px; }
-->
</style>

HTML Code for popup div tags:
<body>
<a href="#" onclick="openpopup('popup1')">Open Popup Div #1</a>
<div id="popup1" class="popup">
Popup Div Tag #1 content goes here!
</div>

<a href="#" onclick="openpopup('popup2')">Open Popup Div #2</a>
<div id="popup2" class="popup">
Popup Div Tag #2 content goes here!
</div>

<div id="bg" class="popup_bg"></div>
</body>

Every popup window on a page should have a unique id and that same id should be used in the onclick() event of the link. You can even put other div containers inside the popup div or use iframes to display content from other pages.

Monday, June 1, 2009

Center align Div tags horizontally and vertically at Page center using JavaScript

It is easy to horizontally center align div tags on a page by using fixed width and auto left & right margins, but there is no efficient CSS technique which aligns the div tag at vertical center of the page. Though you can use CSS properties like display:table-cell combined with vertical-align:middle to align it roughly at the vertical center but it isn’t always accurate and scalable for div tags with different sizes.

My technique utilizes JavaScript functionalities to change CSS properties on the fly for aligning the Div tag at the page center based upon the current window size. Left and Top coordinates for the div tag are calculated on the fly based upon the window and div tag size. The JavaScript function reads the CSS properties for the div tag from the Stylesheet or inline styles and calculated the coordinates respectively.

Horizonally and Vertically Center Aligned Div Tag

Here is the complete HTML/JavaScript Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Center Aligned div</title>
<style type="text/css">
<!--
#mydiv {
      background-color: #CCC;
      height: 200px;
      width: 400px;
      position: absolute;
      padding: 10px;
}
-->
</style>
<script language="javascript">
function center_align(id){
      //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;
      }
      }
      var divobj = document.getElementById(id);
      //For CSS StyleSheet use:
      if (navigator.appName=="Microsoft Internet Explorer")
      computedStyle = divobj.currentStyle;
      else computedStyle = document.defaultView.getComputedStyle(divobj, null);
      //Get Div width and height from StyleSheet
     
var divWidth = computedStyle.width.replace('px', '');

      var divHeight = computedStyle.height.replace('px', '');
      //For Inline styling use:
      //var divWidth =  divobj.style.width.replace('px', '');
      //var divHeight =  divobj.style.height.replace('px', '');
      var divLeft = (pageWidth - divWidth) / 2;
      var divTop = (pageHeight - divHeight) / 2;
      //Set Left and top coordinates for the div tag

      divobj.style.left = divLeft + "px";
      divobj.style.top = divTop + "px";
      divobj.innerHTML = "Page Width:"+pageWidth+"<br />Page Height:"+pageHeight;
      divobj.innerHTML += "<br /><br />Div Width:"+divWidth+"<br />Div Height:"+divHeight;
}
</script>
</head>
<body >
<div id="mydiv">
<a onclick="center_align('mydiv')" href="#">Put me at Page Center!</a>
</div>
</body>
</html>

If you are using inline styling for the div tag as follows:
<div id="mydiv" style="width: 400px; height: 200px; background-color: #CCC; position: absolute; padding: 10px;">
You can just use the var divWidth =  divobj.style.width.replace('px', ''); method to retrieve the width and height of the div tag, instead of using the computedStyle object.

You can also use the center_align() function with onload() event inside body tag to automatically align it at page center when the page loads.

JavaScript Pop-up window

JavaScript window object supports an open method to open a new browser window. The syntax for window.open method is as follows:

window.open("URL", "Target")

If the second argument doesn’t identify an existing window or frame, a new window or tab is created based upon the string passed in the third argument. With a missing third argument in window.open, the new window/tab is opened with the default browser window properties.

So, to open a pop-up window using JavaScript, the second argument for location should not match with any existing window or frame id, and the popup window size and properties can be assigned using a comma delimited string in the third argument:

window.open("URL","newpopup", "height=400,width=400,top=50,left=50,resizable=no");

This code opens a non resizable window that’s 400 X 400 and positioned 50 pixels from the top and left
of the screen. Here is the list of all the properties that can be set for the new pop-up window:

Setting

Values

Description

fullscreen

yes/no

Browser window should be maximized or not.

height

number

Initial height of the new window (minimum 100).

width

number

Initial width of the new window (minimum 100).

top

number

Initial top coordinate (no negative number)

left

number

Initial left coordinate (no negative number).

menubar

yes/no

Display menu bar or not.

resizable

yes/no

Window can be resized or not.

scrollbars

yes/no

Display scroll bar or not.

status

yes/no

Display status bar or not.

toolbar

yes/no

Display tool bar or not.

location

yes/no

Display location entry field or not.

The window.open() method also returns a reference to the newly created window. This reference object can be used to manipulate the newly opened window properties.

var popup =window.open("URL","newpopup", "height=400,width=400,resizable=yes");
//resize it
popup.resizeTo(500, 500);
//resize by
popup.resizeBy(100, 100);
//move it
popup.moveTo(100, 100);
//move by
popup.moveBy(100, 100);
//write to the new popup window
popup.document.write("<h1>New PopUp Window</h1>");
//close it
popup.close();

Here is an example code for Pop-Up window:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Popup Test</title>
<script type="text/javascript">
<!--
function popup() {
   var width = 300;
   var height = 200;
   var prop = 'width=' + width + ', height=' + height;
   prop += ', top=50, left=50';
   prop += ', location=no';
   prop += ', menubar=no';
   prop += ', resizable=no';
   prop += ', status=no';
   prop += ', toolbar=no';
   var newpopup = window.open('', 'newpopup', prop);
   newpopup.document.write("<h1>New PopUp Window</h1>");
   newpopup.document.write("<br /><a href='#' onclick='javascript:window.close()'>Close Me</a>");
   if (window.focus) { newpopup.focus() }
   return false;
}
// -->
</script>
</head>
<body>
<a href="javascript: void(0)" onclick="popup()">Pop-Up</a>
</body>
</html>

Technorati Tags:

Browser Window size using JavaScript

Determining the size of a window cross-browser is not straightforward. Firefox, Safari, Opera, and Chrome all provide four properties: innerWidth , innerHeight , outerWidth , and outerHeight.

  • Safari and Firefox: outerWidth and outerHeight return the dimensions of the browser window itself.
  • Opera: outerWidth and outerHeight return the size of the page view container.
  • Chrome: outerWidth and outerHeight return the size of the viewport
  • IE: offers no way to get the current dimensions of the browser window; however, it does provide information about the viewable area of the page via the DOM, document.documentElement.clientWidth and document.documentElement.clientHeight.

The document.documentElement.clientWidth and document.documentElement.clientHeight properties provide the width and height of the page viewport in IE, Firefox, Safari, Opera, and Chrome. So, a generalized method for retrieving the browser window width and height is given below:

var pageWidth = window.innerWidth, 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;
    }
}

Technorati Tags: