Home  >  Article  >  Web Front-end  >  How to Center a Popup Window on Screen in Both Single and Dual Monitor Setups?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-31 19:11:02468browse

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>

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>

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!

Statement:
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