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

How to Center a Popup Window in the User\'s Screen Using JavaScript?

DDD
Release: 2024-11-01 06:33:02
Original
999 people have browsed it

How to Center a Popup Window in the User's Screen Using JavaScript?

How to Center a Popup Window in the User's Screen Using JavaScript

To center a popup window opened using the window.open function, it's important to take into account the user's current screen resolution. Here's a solution that effectively centers the window on both single and dual-monitor setups:

<code class="javascript">const popupCenter = ({url, title, w, h}) => {
    // Handle dual-screen position
    const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : window.screenX;
    const dualScreenTop = window.screenTop !== undefined ? window.screenTop : window.screenY;

    // Get browser window dimensions
    const width = window.innerWidth || document.documentElement.clientWidth || screen.width;
    const height = window.innerHeight || document.documentElement.clientHeight || screen.height;

    // Account for system zoom to obtain accurate dimensions
    const systemZoom = width / window.screen.availWidth;
    const left = (width - w) / 2 / systemZoom + dualScreenLeft
    const top = (height - h) / 2 / systemZoom + dualScreenTop
    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.example.com', title: 'Popup Window', w: 500, h: 300}); </code>
Copy after login

This code snippet opens a popup window centered on the user's screen, with a specified URL, title, width, and height.

The above is the detailed content of How to Center a Popup Window in the User\'s Screen Using JavaScript?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template