'Center popup windows opened from main window using jquery?
In a web application I have lots of popup windows opened at different points. These are normal popup windows opened using window.open() and not Jquery popup windows. They open at different positions on the browser window and are also of different height and width.
Now, I would like to center all the popup windows when opened on the browser. I have written a function which would return me the top and left values for centering for passed height and width. Now, I need to call this function once before every time i use window.open to open the popup window, get the top and left values and then pass them to window.open. I might end up doing this in many places in various javascript files.
Is there a generic way of achieving my requirement with few changes the centering up of all popup windows opened using window.open. Can Jquery help me to do this easily?
Solution 1:[1]
I think this is similar to what you currently have, but you might want to take a look. Doesn't seem like there's much need to use jQuery link
function PopupCenter(pageURL, title,w,h) {
var left = (screen.width/2)-(w/2);
var top = (screen.height/2)-(h/2);
var targetWin = window.open (pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
}
Solution 2:[2]
Just transform your code from
var params = getCenteredCoords();
window.open(url, "...", params+"...");
to
myPopup(url, "...", "...");
and declare a global
function myPopup(url, name, params) {
var coords = getCenteredCoords();
return window.open(ul, name, coords+params);
}
And yes, you will need your custom solution in every of those files. So the only way is not to repeat yourself and use one global function.
OK, there is a way not to change everything in all your files: Overwrite window.open with your custom solution:
window.open = (function(original){
return function myPopup(url, name, params) {
var coords = getCenteredCoords();
return original(ul, name, coords+params);
};
})(window.open);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jason Kulatunga |
| Solution 2 | Bergi |
