Skip to content

Instantly share code, notes, and snippets.

@ianpgall
Created March 11, 2014 17:49
Show Gist options
  • Save ianpgall/9491174 to your computer and use it in GitHub Desktop.
Save ianpgall/9491174 to your computer and use it in GitHub Desktop.
JavaScript function that can center a window opened with window.open
var openWindow = function (url, name, width, height, options) {
"use strict";
var finalOptions, opts, winTop, winLeft, finalTop, finalLeft, winHeight, winWidth;
finalOptions = [];
if (!options) {
options = "";
}
// Make sure width is a number, else default to 400
width = +width;
if (isNaN(width)) {
width = 400;
}
// Make sure height is a number, else default to 400
height = +height;
if (isNaN(height)) {
height = 400;
}
if (options.indexOf("top=") < 0) {
// If options doesn't contain "top" spec, define it
winTop = +(window.screenY || window.screenTop || 50);
winHeight = +(window.outerHeight || window.innerHeight || 500);
finalTop = (winTop + ((winHeight / 2) - (height / 2)));
finalOptions.push("top=" + finalTop);
}
if (options.indexOf("left=") < 0) {
// If options doesn't contain "left" spec, define it
winLeft = +(window.screenX || window.screenLeft || 50);
winWidth = +(window.outerWidth || window.innerWidth || 500);
finalLeft = (winLeft + ((winWidth / 2) - (width / 2)));
finalOptions.push("left=" + finalLeft);
}
finalOptions.push("height=" + height);
finalOptions.push("width=" + width);
opts = finalOptions.join(",") + (options ? "," + options : "");
return window.open(url, name, opts);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment