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 window.open
.
To do this, we write:
const popupCenter = ({
url,
title,
w,
h
}) => {
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 = window.open(url, title,
`
scrollbars=yes,
width=${w / systemZoom},
height=${h / systemZoom},
top=${top},
left=${left}
`
)
if (window.focus) {
newWindow.focus();
}
}
popupCenter({
url: 'http://www.yahoo.com',
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 window.open
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.
Conclusion
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.