Home >Web Front-end >JS Tutorial >How to Center a Popup Window on Screen in Both Single and Dual Monitor Setups?
To center a popup window on screen, we can utilize JavaScript's window.open function and some additional calculations to determine the exact x and y coordinates based on the current screen resolution.
For both single and dual-monitor setups, the following function effectively centers the popup window horizontally while accounting for the possibility of it not being fully maximized:
<code class="javascript">const popupCenter = ({url, title, w, h}) => { // Adjust for dual-screen position const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : window.screenX; const dualScreenTop = window.screenTop !== undefined ? window.screenTop : window.screenY; // Calculate available screen dimensions 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 centered coordinates const left = (width - w) / 2 / systemZoom + dualScreenLeft const top = (height - h) / 2 / systemZoom + dualScreenTop // Open the new window const newWindow = window.open(url, title, ` scrollbars=yes, width=${w / systemZoom}, height=${h / systemZoom}, top=${top}, left=${left} ` ) // Bring the new window to focus if (window.focus) newWindow.focus(); }</code>
To center a popup window at screen resolution 900x500 with the title "XTF":
<code class="javascript">popupCenter({url: 'http://www.xtf.dk', title: 'XTF', w: 900, h: 500});</code>
The above is the detailed content of How to Center a Popup Window on Screen in Both Single and Dual Monitor Setups?. For more information, please follow other related articles on the PHP Chinese website!