Javascript Tricks, Samples, Tutorials & Howtos

New versions notifications available via

Follow jtricksdotcom on Twitter
/ JTricks.com / Window management / Centered Popup Box
Last updated: 03 Jul 2007
Centered Popup Box
This script will display a centered box with given width and height with the contents of a separate page. It is best suited to display an advertisement, quick site menu or other form of content navigation.

It could be used to display a box upon clicking on a hyperlink or on any other event such as page load.
Script demonstration
Page history . Site map
Script source code
To use the script perform the following steps:

  • Create separate page(s), which will open in separate box(es). Be sure to create all hyperlinks in those pages with target="_top" unless you want to create mini-navigation in those box(es).
  • Be sure to specify background (colour) for these pages, otherwise you would get transparent boxes in some browsers.
  • Insert the following code somewhere on the page (or put in separate file and reference it):
<script type="text/javascript"><!--
/* Script by: www.jtricks.com
 * Version: 20070703
 * Latest version:
 * www.jtricks.com/javascript/window/box_centered.html
 */
var has_inner = typeof(window.innerWidth) == 'number';
var has_element = document.documentElement
    && document.documentElement.clientWidth;

// Moves the box object to be centered on current
// viewable area of the page
function center_box(box, width, height)
{
    cleft = has_inner
        ? pageXOffset + 
          (window.innerWidth - width)/2
        : has_element
          ? document.documentElement.scrollLeft + 
            (document.documentElement.clientWidth - width)/2
          : document.body.scrollLeft + 
            (document.body.clientWidth - width)/2;

    ctop = has_inner
        ? pageYOffset + (window.innerHeight - height)/2
        : has_element
          ? document.documentElement.scrollTop + 
            (document.documentElement.clientHeight - height)/2
          : document.body.scrollTop + 
            (document.body.clientHeight - height)/2;

    box.style.left = cleft > 0 ? cleft + 'px' : '0px';
    box.style.top = ctop > 0 ? ctop + 'px' : '0px';
}

// Hides other alone popup boxes that might be displayed
function hide_other_alone(obj)
{
    if (!document.getElementsByTagName)
        return;

    var all_divs = document.body.getElementsByTagName("DIV");

    for (i = 0; i < all_divs.length; i++)
    {
        if (all_divs.item(i).style.position != 'absolute' ||
            all_divs.item(i) == obj ||
            !all_divs.item(i).alonePopupBox)
        {
            continue;
        }

        all_divs.item(i).style.display = 'none';
    }
    return;
}

// Shows a box if it wasn't shown yet or is hidden
// or hides it if it is currently shown
function show_hide_centered_box(an, width, height, borderStyle)
{
    show_hide_centered_href(
        an.href, width, height, borderStyle);
    return false;
}

// Shows a box if it wasn't shown yet or is hidden
// or hides it if it is currently shown
function show_hide_centered_href(href, width, height, borderStyle)
{
    var boxdiv = document.getElementById(href);

    if (boxdiv != null)
    {
        if (boxdiv.style.display=='none')
        {
            hide_other_alone(boxdiv);
            // Show existing box, move it
            // if document changed layout
            center_box(boxdiv, width, height);
            boxdiv.style.display='block';

            // Workaround for Konqueror/Safari
            if (!boxdiv.contents.contentWindow)
                boxdiv.contents.src = href;
        }
        else
            // Hide currently shown box.
            boxdiv.style.display='none';
        return false;
    }

    hide_other_alone(null);

    // Create box object through DOM
    boxdiv = document.createElement('div');

    // Assign id equalling to the document it will show
    boxdiv.setAttribute('id', href);

    // Add object identification variable
    boxdiv.alonePopupBox = 1;

    boxdiv.style.display = 'block';
    boxdiv.style.position = 'absolute';
    boxdiv.style.width = width + 'px';
    boxdiv.style.height = height + 'px';
    boxdiv.style.border = borderStyle;
    boxdiv.style.textAlign = 'right';
    boxdiv.style.padding = '4px';
    boxdiv.style.background = '#FFFFFF';
    document.body.appendChild(boxdiv);

    var offset = 0;

    // Remove the following code if 'Close' hyperlink
    // is not needed.
    var close_href = document.createElement('a');
    close_href.href = 'javascript:void(0);';
    close_href.onclick = function()
    {
        show_hide_centered_href(href, width, height, borderStyle);
    }

    close_href.appendChild(document.createTextNode('Close'));
    boxdiv.appendChild(close_href);
    offset = close_href.offsetHeight;
    // End of 'Close' hyperlink code.

    var contents = document.createElement('iframe');
    //contents.scrolling = 'no';
    contents.overflowX = 'hidden';
    contents.overflowY = 'scroll';
    contents.frameBorder = '0';
    contents.style.width = width + 'px';
    contents.style.height = (height - offset) + 'px';

    boxdiv.contents = contents;
    boxdiv.appendChild(contents);

    center_box(boxdiv, width, height);

    if (contents.contentWindow)
        contents.contentWindow.document.location.replace(
            href);
    else
        contents.src = href;

    // The script has successfully shown the box,
    // prevent hyperlink navigation.
    return;
}

//--></script>
  • If Close hyperlink inside the box is not needed, remove the apropriately marked code block.
If you would like to show boxes upon a hyperlink click do the following:

  • Add hyperlinks leading to your separate pages. Add onclick handler to those hyperlinks. The handler should call show_hide_box function with four parameters. The first should always be this. The second is width of the box in pixels, the third - height and the last one - border style. For example:
<a href="box_demo_history.html"
   onclick="return show_hide_box(this, 200, 270, '2px solid')">
Page history
</a>
If you would like to show a box upon page load do the following:

  • Add the call to show_hide_centered_href(<target page>, <width>, <height>, <border style>) to onload attribute of the BODY tag of your HTML page. For example:
<body
   onload="show_hide_href('test.html', 200, 200, '2px solid')">
  • Be sure to verify page design with the Javascript turned off.
Browser compatibility
The javascript snippet above was tested on the following user agents:

Mozilla/Netscape Firefox 2.0.x Ok.
Firefox 1.5 Ok.
Firefox 1.0.x An extra record is inserted into browser history. The browser back button might not work correctly.
Netscape Navigator 4.79 Downgrades gracefully *.
Microsoft Internet Explorer 7.0 Ok.
Internet Explorer 6.0 Ok.
Opera Opera 8.x Ok.
Opera 9.x Ok.
KHTML Konqueror 3.5.5 An extra record is inserted into browser history. The browser back button might not work correctly.
No Javascript or
Javascript turned off
Any Downgrades gracefully *.

*: Graceful degradation means the user agent navigates to target web page instead of showing it in popup box pon hyperlink click and the box just isn't shown for page load if it was specified in onload attribute of BODY tag.
See Also
Absolute Popup Box - If you want to have several boxes visible at the same time appearing under clicked hyperlink.
Donations and Script Rating
If you like our script, please
or at least rate it @ hotscripts.com!