Home  >  Article  >  Web Front-end  >  How Can I Center a Popup Window on the Screen Using JavaScript?

How Can I Center a Popup Window on the Screen Using JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-30 10:30:02814browse

How Can I Center a Popup Window on the Screen Using JavaScript?

Centering a Popup Window

Centering a popup window on the screen can be achieved using JavaScript's window.open function. The exact coordinates (x and y) at which the window will appear vary based on the current screen resolution.

Cross-Platform Solution

The following solution works for both single and dual-monitor setups:

<code class="js">const popupCenter = ({ url, title, w, h }) => {
  // Adjust for dual-screen positions
  const dualScreenLeft = window.screenLeft || window.screenX;
  const dualScreenTop = window.screenTop || window.screenY;

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

  // Calculate the scaling factor
  const systemZoom = width / window.screen.availWidth;

  // Calculate the window's position
  const left = (width - w) / 2 / systemZoom + dualScreenLeft;
  const top = (height - h) / 2 / systemZoom + dualScreenTop;

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

  // Focus the new window
  if (window.focus) newWindow.focus();
};</code>

Usage Example

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

Credit

This solution is adapted from http://www.xtf.dk/2011/08/center-new-popup-window-even-on.html.

The above is the detailed content of How Can I Center a Popup Window on the Screen Using JavaScript?. 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