简体   繁体   中英

how to use inline javascript code to auto center pop up window

I have a in line javascript used in AJAX, would like to auto center when open, but make the change in the inline scriprt only. Is that possible? Here's my code:

<a href='javascript:void(0)' title='owner' onclick=\"window.open('owner.html','owner','height=320, width=300,location=no,scrollbars=yes')\ >some text</a>

You need to calculate left and top and supply the computed values as parameters to the window.open() call. I'm not sure why you want the JavaScript to be inline, it better be done in a separate call so that you can invoke the same function from all places.

Left = (screen.width / 2) - (Provided Width of the Popup / 2)
Top  = (screen.height / 2) - (Provided Height of the Popup / 2)   

Posting only the relevant code -

window.open('owner.html','owner','height=320, width=300,location=no,scrollbars=yes,left=' + (screen.width/2)-(300/2) + ',top=' + (screen.height/2)-(320/2))

I worked with verisimilitude's answer and got this to work:

<a onclick="javascript:void window.open('http://www.google.com','1380642102467','width=400,height=300,resizable=1,left='+(screen.width/2-200)+',top='+(screen.height/2-150));return false;" href="http://www.google.com"><u>CLICK HERE</u></a>

The main difference was in this section:

left='+(screen.width/2-200)+'
top='+(screen.height/2-150)

I found that subtracting the difference of the window size worked if half the window size were subtracted within the (screen.) parameter. The -200 and -150 parts are calculated from half the size of my pop-up window (as manually entered in the "width" and "height"). I don't know if there is a more dynamic way to this based on varying pop-up window sizes, but I personally don't need it to do that and am fine with entering a static value.

I needed this to be completely inline as well. The place where I need to use this does not allow changing the head or adding additional files. I am restricted to upload body HTML only.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM