Centered Popup

We work on a lot of websites for wine companies that require legal footer links to open in a popup. Working with multiple monitors all the time, I didn’t enjoy having to go off-screen to find the little x to close. Daniel wrote a nice function that will open the window / popup perfectly centered in the middle of your screen. This is also perfect for opening up windows when using social share functionality.

The Function

Copy and paste the function below into your JavaScript file.

function PopupCenter(url, title, w, h, options) {
	options = options || 'scrollbars=yes';
	// Fixes multi-monitor position                         Most browsers      Firefox
	var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
	var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;
	var left = ((window.innerWidth / 2) - (w / 2)) + dualScreenLeft;
	var top = ((window.innerHeight / 2) - (h / 2)) + dualScreenTop;
	var newWindow = window.open(
		url,
		title,
		options + ', width=' + w + ', height=' + h + ', top=' + top + ', left=' + left
	);
	
	// Puts focus on the newWindow
	if (window.focus) {
		newWindow.focus();
	}
}

How I use it

document.addEventListener('click', function (e) {
	if (e.target.matches('.legal-link')) {
		e.preventDefault();
		PopupCenter(e.target.getAttribute('href'), 'popup', 650, 550)
	}
});