Pages

Thursday, August 18, 2011

Center a new popup window even on dualscreen with javascript

function PopupCenter(url, title, w, h) {
    // Fixes dual-screen position                         Most browsers      Firefox
    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, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);

    // Puts focus on the newWindow
    if (window.focus) {
        newWindow.focus();
    }
}
Usage example:
PopupCenter('http://www.xtf.dk','xtf','900','500');
UPDATE: It will also work on minimized windows

7 comments:

  1. Just wanted to say thanks for this! It works great!

    ReplyDelete
  2. ...and thanks from me too! It works well and centres a pop-up within the 'parent' page - unless the parent is smaller than the pop-up! Can I suggest that the pop-up is centred on the center of the parent?

    ReplyDelete
  3. Thank you for this, it works great !!! It's exactly what I want !!!

    ReplyDelete
  4. I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business. Search Bar Firefox 57 Quantum addon

    ReplyDelete