JavaScript Answers

How to Center a Browser Popup Window on the Screen with JavaScript?

Spread the love

Sometimes, we want to open a popup window in our JavaScript web app.

And we may want to center the popup on the screen.

In this article, we’ll look at how to center a browser popup window on the screen with JavaScript.

Center a Browser Popup Window on the Screen with JavaScript

To center a browser popup window on the screen, we’ve to do some calculations and pass the results into the options string that we pass into .

To do this, we write:

const popupCenter = ({
}) => {
  const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : window.screenX;
  const dualScreenTop = window.screenTop !== undefined ? window.screenTop : window.screenY;

  const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
  const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;

  const systemZoom = width / window.screen.availWidth;
  const left = (width - w) / 2 / systemZoom + dualScreenLeft
  const top = (height - h) / 2 / systemZoom + dualScreenTop
  const newWindow =, title,
      width=${w / systemZoom},
      height=${h / systemZoom},

  if (window.focus) {

  url: '',
  title: 'yahoo',
  w: 900,
  h: 500

We create the dualScreenLeft and dualScreenTop variables to shift the center of to left corner of the popup in case the user has 2 screens instead of one.

dualScreenLeft is calculated by getting screenLeft or screenX .

dualScreenTop is calculated by getting screenTop or screenY .

Then we calculate the width of the popup with the clientWidth , innerWidth , or screen.width .

The height of the popup is set to the clientHeight , innerHeight or scree.height .

Then we get the zoom level of the screen with the systemZoom variable.

Next, we calculate the coordinates of the top left corner with the left and top variables.

We calculate the left value by setting the width adjusted for the zoom level.

Then we shift the screen with dualScreenLeft in case we’re showing the window on the 2nd screen.

And we do a similar calculation to calculate top .

Next, we call with the systemZoom and the top and left values.

And we call focus on the newWindow if the focus method exists.

Now when we call the popupCenter method, we see the popup centered regardless of whether we have one or 2 screens.


We can center a browser popup screen by making some calculations to get the coordinates of the top left corner of the popup on the screen and its width and height.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *