Tuesday, 30 August 2011

JavaScript set a popup div at center of screen


GetWindowCentered(document.getElementById('popup_div'),500,400);

//Set a div at center of screen
function GetWindowCentered(ctlPopup, popupWidth, popupHeight)
{
      var availHeight = 0;
      var availWidth = 0;
     
      try
      {
          if(typeof(window.innerWidth) == 'number'){
                availHeight = window.innerHeight;
                availWidth = window.innerWidth;
          }else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)){
                availHeight = document.documentElement.clientHeight;
                availWidth = document.documentElement.clientWidth;
          }else if(document.body && (document.body.clientWidth || document.body.clientHeight)){
                availHeight = document.body.clientHeight;
                availWidth = document.body.clientWidth;
          }

          var WinTop = (availHeight - popupHeight)/2;
          var WinLeft = (availWidth - popupWidth)/2;
     
          if(WinTop < 0) WinTop = 0;
          if(WinLeft < 0) WinLeft = 0;               
          ctlPopup.style.top = WinTop + document.body.scrollTop+ "px";
          ctlPopup.style.left = WinLeft + "px";
      }
    catch(err){}
}

No comments:

Post a Comment