How to Position a Popup Window Precisely in the Center of the Screen
Centering a popup window created using JavaScript's window.open function on the screen is essential for optimal user experience. The exact coordinates depend on the screen resolution, so a dynamic solution is required.
Solution: Utilize a Single/Dual Monitor Function
A robust solution that accommodates both single and dual monitor setups is given below:
const popupCenter = ({ url, title, w, h }) => {
// Determine the positions based on screen resolution
const dualScreenLeft = window.screenLeft || window.screenX;
const dualScreenTop = window.screenTop || window.screenY;
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 the centered coordinates
const left = (width - w) / 2 / systemZoom dualScreenLeft;
const top = (height - h) / 2 / systemZoom dualScreenTop;
// Open the popup window with the calculated dimensions and positioning
const newWindow = window.open(url, title,
`
scrollbars=yes,
width=${w / systemZoom},
height=${h / systemZoom},
top=${top},
left=${left}
`
);
if (window.focus) newWindow.focus();
};
Usage Example:
popupCenter({ url: 'http://www.xtf.dk', title: 'xtf', w: 900, h: 500 });
Credits and Source:
This solution, originally from http://www.xtf.dk/2011/08/center-new-popup-window-even-on.html, effectively handles popup window centering for a variety of screen configurations.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3