Javascript Window open() Method opens a popup window. How to center this window on the screen?
A solution could be the following function:
CenterWindow
<script>
/**
* Opens window screen centered.
* @param windowWidth the window width in pixels (integer)
* @param windowHeight the window height in pixels (integer)
* @param windowOuterHeight the window outer height in pixels (integer)
* @param url the url to open
* @param wname the name of the window
* @param features the features except width and height (status, toolbar, location, menubar, directories, resizable, scrollbars)
*/
function CenterWindow(windowWidth, windowHeight, windowOuterHeight, url, wname, features) {
var centerLeft = parseInt((window.screen.availWidth - windowWidth) / 2);
var centerTop = parseInt(((window.screen.availHeight - windowHeight) / 2) - windowOuterHeight);
var misc_features;
if (features) {
misc_features = ', ' + features;
}
else {
misc_features = ', status=no, location=no, scrollbars=yes, resizable=yes';
}
var windowFeatures = 'width=' + windowWidth + ',height=' + windowHeight + ',left=' + centerLeft + ',top=' + centerTop + misc_features;
var win = window.open(url, wname, windowFeatures);
win.focus();
return win;
}
</script>
Usage
Here is an example
<a href="javascript:void(0)"
onclick="CenterWindow(1000,800,50,'http://www.pontikis.net','demo_win');">Click here</a>
Entrepreneur | Full-stack developer | Founder of MediSign Ltd. I have over 15 years of professional experience designing and developing web applications. I am also very experienced in managing (web) projects.