Home > Web Front-end > JS Tutorial > body text

How to Center a Popup Window in the Browser?

Linda Hamilton
Release: 2024-10-31 06:20:02
Original
399 people have browsed it

How to Center a Popup Window in the Browser?

How to Position a Popup Window Precisely in the Center of the Screen

Centering a popup window created using JavaScript's window.open function on the screen is essential for optimal user experience. The exact coordinates depend on the screen resolution, so a dynamic solution is required.

Solution: Utilize a Single/Dual Monitor Function

A robust solution that accommodates both single and dual monitor setups is given below:

<code class="javascript">const popupCenter = ({ url, title, w, h }) => {
    // Determine the positions based on screen resolution
    const dualScreenLeft = window.screenLeft || window.screenX;
    const dualScreenTop = window.screenTop || window.screenY;

    const width = window.innerWidth || document.documentElement.clientWidth || screen.width;
    const height = window.innerHeight || document.documentElement.clientHeight || screen.height;

    // Adjust for system zoom
    const systemZoom = width / window.screen.availWidth;

    // Calculate the centered coordinates
    const left = (width - w) / 2 / systemZoom + dualScreenLeft;
    const top = (height - h) / 2 / systemZoom + dualScreenTop;

    // Open the popup window with the calculated dimensions and positioning
    const newWindow = window.open(url, title,
        `
        scrollbars=yes,
        width=${w / systemZoom},
        height=${h / systemZoom},
        top=${top},
        left=${left}
        `
    );

    if (window.focus) newWindow.focus();
};</code>
Copy after login

Usage Example:

<code class="javascript">popupCenter({ url: 'http://www.xtf.dk', title: 'xtf', w: 900, h: 500 }); </code>
Copy after login

Credits and Source:

This solution, originally from http://www.xtf.dk/2011/08/center-new-popup-window-even-on.html, effectively handles popup window centering for a variety of screen configurations.

The above is the detailed content of How to Center a Popup Window in the Browser?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!