Centered Popup

April 22, 2020
By

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 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 width = $(window).width();
	var height = $(window).height();
	var left = ((width / 2) - (w / 2)) + dualScreenLeft;
	var top = ((height / 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).on('click', '.legal-link', function (e) {
	e.preventDefault();
	var legalLink = $(this).attr('href');
	PopupCenter(legalLink, 'popup', 650, 550);
});