Quick and Dirty JavaScript Pop-Up Windows

by Terri Ann on November 9, 2007

Our topic today: JavaScript pop-up windows.

I have a quick and dirty method I usually use to create JavaScript pop-up windows. I use it because it allows the user to still access the page if they have JavaScript turned off and it centers the window on the screen.
The function accepts 3 parameters the URL, window width and window height. Originally I had used it for a photo gallery script I had written where I needed a way to open each photo in a specifically sized window without overloading the page with excessive functions or code.

The JavaScript function looks like this:

<script language="javascript" type="text/javascript">
<!-- Begin Script
function popWin(URL, winWidth, winHeight) {
    var day = new Date();
    var id = day.getTime();
    var winLeft = screen.width/2 - winWidth/2;
    var winTop = screen.height/2 - winHeight/2;

    eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=" + winWidth + ",height=" + winHeight + ",left=" + winLeft + ",top=" + winTop + "');");    
    eval("page" + id + ".focus()");
}
// End Script -->
</script>

With links formed like so:

<a href="page_to_open.html" onclick="popWin(this.href, 650, 450); return false;">Open pop-up window</a>

Nothing terribly special but it’s a quick-and dirty way to create simply customizable windows in a flash!

Related Links

{ 1 comment… read it below or add one }

1 Amy November 28, 2007 at 2:46 pm

Great sample to have onhand!

Another thing you can do is have that function return false and then your onclick can just return the function.

Like this:

function popWin(URL, winWidth, winHeight) {
    [...]
    eval("page" + id + ".focus()");
    return false;
}
[...]
<a href="page_to_open.html" onclick="return popWin(this.href, 650, 450);">Open pop-up window</a>

Leave a Comment

Previous post:

Next post: