How to Center a Popup Window on Screen

By FoxLearn 2/8/2025 2:23:29 AM   35
You can use JavaScript's window.open() method to create and center a popup window. By setting the correct values for left and top, we can position the window in the middle of the screen.

In this example, the popup window will open at the bottom right corner of the screen, without centering.

<!DOCTYPE html>
<html>
<head>
    <title>
        Non-centered Popup Window
    </title>
</head>
<body>
    <h1>Sample Code Example</h1>
    <p>This is a non-centered popup window.</p>

    <script>
        function createPopupWindow(pageURL, pageTitle, popupWinWidth, popupWinHeight) {
            let left = screen.width - popupWinWidth;
            let top = screen.height - popupWinHeight;
            let myWindow = window.open(pageURL, pageTitle,
                'resizable=yes, width=' + popupWinWidth
                + ', height=' + popupWinHeight + ', top='
                + top + ', left=' + left);
        }
    </script>

    <button onclick="createPopupWindow('https://www.example.com', 'Example Website', 800, 600);">
        Open Example Website
    </button>
</body>
</html>

To Center the Popup Window:

Now, let's adjust the popup window so that it opens at the center of the screen. We'll calculate the left and top values as follows:

  • left = (screen.width - popupWinWidth) / 2
  • top = (screen.height - popupWinHeight) / 3

Here's the updated code to center the popup window:

<!DOCTYPE html>
<html>
<head>
    <title>
        Centered Popup Window
    </title>
</head>
<body>
    <h1>Centered Popup Window Example</h1>
    <p>This popup window will appear in the center of the screen.</p>

    <script>
        function createPopupWindow(pageURL, pageTitle, popupWinWidth, popupWinHeight) {
            let left = (screen.width - popupWinWidth) / 2;
            let top = (screen.height - popupWinHeight) / 3;

            let myWindow = window.open(pageURL, pageTitle,
                'resizable=yes, width=' + popupWinWidth
                + ', height=' + popupWinHeight + ', top='
                + top + ', left=' + left);
        }
    </script>

    <button onclick="createPopupWindow('https://www.example.com', 'Example Website', 800, 600);">
        Open Example Website
    </button>
</body>
</html>

How This Works:

  • The popup window opens with the specified size (800px by 600px).
  • The calculation (screen.width - popupWinWidth) / 2 ensures the window is horizontally centered on the screen.
  • Similarly, (screen.height - popupWinHeight) / 3 positions it more evenly on the vertical axis.

Now when you click the button, the popup window will appear in the center of your screen.