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

How to Center a Popup Window on Screen in Both Single and Dual Monitor Setups?

Mary-Kate Olsen
Release: 2024-10-31 19:11:02
Original
405 people have browsed it

How to Center a Popup Window on Screen in Both Single and Dual Monitor Setups?

How to Center a Popup Window on Screen

To center a popup window on screen, we can utilize JavaScript's window.open function and some additional calculations to determine the exact x and y coordinates based on the current screen resolution.

Single/Dual Monitor Function

For both single and dual-monitor setups, the following function effectively centers the popup window horizontally while accounting for the possibility of it not being fully maximized:

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

  // Calculate available screen dimensions
  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 centered coordinates
  const left = (width - w) / 2 / systemZoom + dualScreenLeft
  const top = (height - h) / 2 / systemZoom + dualScreenTop

  // Open the new window
  const newWindow = window.open(url, title, 
    `
    scrollbars=yes,
    width=${w / systemZoom}, 
    height=${h / systemZoom}, 
    top=${top}, 
    left=${left}
    `
  )

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

Usage Example

To center a popup window at screen resolution 900x500 with the title "XTF":

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

The above is the detailed content of How to Center a Popup Window on Screen in Both Single and Dual Monitor Setups?. 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!