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

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

Mary-Kate Olsen
Release: 2024-10-30 10:30:02
Original
813 people have browsed it

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>
Copy after login

Usage Example

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

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!

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!