javascript center?

Discussion in 'JavaScript' started by izlik, Feb 24, 2009.

  1. #1
    Hello. the javascript code bellow is for a popup window. currently the popup appears at the top left of my screen, how can i make it center itself once it popups?

    <SCRIPT TYPE="text/javascript">
    <!--
    function popup(mylink, windowname)
    {
    if (! window.focus)return true;
    var href;
    if (typeof(mylink) == 'string')
       href=mylink;
    else
       href=mylink.href;
    window.open(href, windowname, 'width=400,height=200,scrollbars=yes');
    return false;
    }
    //-->
    </SCRIPT>
    Code (markup):
    '<A HREF="pop.php?file=$file" onClick="return popup(this)">' . $file . '</A>'
    Code (markup):

     
    izlik, Feb 24, 2009 IP
  2. lp1051

    lp1051 Well-Known Member

    Messages:
    163
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    108
    #2
    Hi izlik,

    try method moveTo(Xcoord, Ycoord). For that you need to hold the opened window in some variable.
    E.g.
    var myWin = window.open(href, windowname, 'width=400,height=200,scrollbars=yes');
    myWin.moveTo(200, 200);
    If you need to center it based on viewport size and window size, just count X and Y coordinates before calling moveTo.
     
    lp1051, Feb 25, 2009 IP
  3. astupidname

    astupidname Peon

    Messages:
    12
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    <html>
    <head>
    
    <script type="text/javascript">
    
    function popup(mylink, windowname,width,height) {
        if (! window.focus) {
            return true;
        }
        var href,
            l = (screen.width / 2) - (width / 2),
            t = (screen.height / 2) - (height / 2);
        if (typeof(mylink) == 'string') {
            href=mylink;
        } else {
            href=mylink.href;
        }
        window.open(href, windowname,'width=' + width + ',height=' + height + ',left=' + l + ',top=' + t + ',scrollbars=yes');
        return false;
    }
    
    </script>
    </head>
    <body>
    <a href="http://www.example.com" onclick="return popup(this,'astupidWindow',400,200);">Go google somebody</a>
    </body>
    </html>
    HTML:
     
    astupidname, Feb 26, 2009 IP
    izlik likes this.