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

15 comments:

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

    ReplyDelete
    Replies
    1. Great Article Cyber Security Projects projects for cse Networking Security Projects JavaScript Training in Chennai JavaScript Training in Chennai The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      Delete
  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
  5. This doesn't work with, old legacy, applications that have nexted framesets or iframes.

    You must add .top to the window calls. IE: window.top.screenLeft

    ReplyDelete
  6. This is what commonly happens to the newbies in the business industry who do not know how to effectively market their product or service or service.cashmio

    ReplyDelete
  7. Nine years later, this is as useful as can be. Thanks a lot.

    ReplyDelete
  8. Go through the partner's portfolio and reviews. Also consider scheduling an appointment with the partner so that you can learn more about him/her. Salesforce training in Chennai

    ReplyDelete