How to Open a JavaScript Centered Popup Window

Ciprian on Tuesday, May 17, 2016 in Methods, Events and Scopes

NEW! Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

This tutorial is about JavaScript popups and how to show a window in the center of the screen and focus on it. The trick is easy and the containing function is small. Here is the JavaScript code:

function window_popup(content, x, y, title) {
    let thisWindow;

    thisWindow = window.open(content, title, "width="+x+", height="+y+", scrollbars=auto, screenX=0, screenY=0, toolbar=no, location=no, menubar=no");

    thisWindow.moveTo((screen.width-x)/2,(screen.height-y)/3);
    thisWindow.window.focus();
}

And here is the caller function:

<a href="#" onclick="window_popup('mypage.html', 400, 300, 'mypage')">Open My Page</a>

Remember to quote the page name and title, otherwise the script will generate an error. Popup window attributes can be changed in the second line of the function

"scrollbars=auto, screenX=0, screenY=0, toolbar=no, location=no, menubar=no"

depending on what the role of the window is.

Related posts

Leave a Reply

You have to agree to the comment policy.