Skip to content

Instantly share code, notes, and snippets.

@abcarroll
Last active August 29, 2015 14:03
Show Gist options
  • Save abcarroll/78e9ba1ba9341ea9dd1e to your computer and use it in GitHub Desktop.
Save abcarroll/78e9ba1ba9341ea9dd1e to your computer and use it in GitHub Desktop.
Perform a window.open, centering it (even for dual monitor setups), and only allow one open instance of each identifier at a time
/*
Pops open a new window given the identifier (name), url, width, height, and
optional additional options (as normally passed to window.open()), centered
on the screen. Additionally, it will not open more than one instance of each
identifier.
Amalgamation of:
https://developer.mozilla.org/en-US/docs/Web/API/Window.open "Best Practices"
http://stackoverflow.com/questions/4068373/center-a-popup-window-on-screen
"Single/Dual Monitor Function"
+ Event handler for .popup-window
- A.B. Carroll <[email protected]>
*/
$(function() {
$.popWindowReferences = [];
$.popWindow = function(name, url, w, h, options) {
var winObjRef = $.popWindowReferences[name];
if(winObjRef == null || winObjRef.closed) {
if(typeof options == "undefined") {
options = "";
} else {
options = "," + options;
}
// Fixes dual-screen position for most browsers
var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;
width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
var left = ((width / 2) - (w / 2)) + dualScreenLeft;
var top = ((height / 2) - (h / 2)) + dualScreenTop;
var newWindow = window.open(url, name, 'width=' + w + ', height=' + h + ', top=' + top + ', left=' + left + options);
// Puts focus on the newWindow
if (window.focus) {
newWindow.focus();
}
// Add it to the stack of references
$.popWindowReferences[name] = newWindow;
} else { // Do not open a new window
winObjRef.focus();
}
};
/* if possible move the delegation off of $(docuemnt)! */
$(document).on('click', '.popup-window', function(event) {
if($(this).data('popup-prevent-default') == true) {
event.preventDefault();
}
$.popWindow($(this).data('popup-name'), $(this).data('popup-url'), $(this).data('popup-width'), $(this).data('popup-height'), $(this).data('popup-options'));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment