Open In App

How to center a popup window on screen?

JavaScript window.open() method is used to open a popup window. This popup window will be placed in the center of the screen.

Example 1: This example creates the pop-up window without placing it into the center. 






<!DOCTYPE html>
<html>
 
<head>
    <title>
        Non-centered popup window
        on the screen
    </title>
</head>
 
<body>
    <h1>GeeksforGeeks</h1>
 
    <p>
        Non-centered popup window
        on the screen
    </p>
 
    <script>
        function createPopupWin(pageURL, pageTitle,
            popupWinWidth, popupWinHeight) {
            let left = (screen.width);
            let top = (screen.height);
            let myWindow = window.open(pageURL, pageTitle,
                'resizable=yes, width=' + popupWinWidth
                + ', height=' + popupWinHeight + ', top='
                + top + ', left=' + left);
        }
    </script>
 
    <button onclick="createPopupWin('https://www.geeksforgeeks.org',
            'GeeksforGeeks Website', 1200, 650);">
        GeeksforGeeks
    </button>
</body>
 
</html>

Output:

Opening popup anywhere at the screen

Center popup window: To center the popup window we are changing the values of parameters of open() method as follows:



Example 2: This example creates the pop up window and placing it into center. 




<!DOCTYPE html>
<html>
 
<head>
    <title>
        Centered popup window
        on the screen
    </title>
</head>
 
<body>
    <h1>GeeksforGeeks</h1>
 
    <p>
        Centered popup window
        on the screen
    </p>
 
    <script>
        function createPopupWin(pageURL, pageTitle,
            popupWinWidth, popupWinHeight) {
            let left = (screen.width - popupWinWidth) / 2;
            let top = (screen.height - popupWinHeight) / 4;
 
            let myWindow = window.open(pageURL, pageTitle,
                'resizable=yes, width=' + popupWinWidth
                + ', height=' + popupWinHeight + ', top='
                + top + ', left=' + left);
        }
    </script>
 
    <button onclick="createPopupWin('https://www.geeksforgeeks.org',
            'GeeksforGeeks Website', 1200, 650);">
        GeeksforGeeks
    </button>
</body>
 
</html>

Output:

Opening popup box at the center of the screen


Article Tags :