1

I am trying to center a popup window with javascript, but it only centers it horizontally, not vertically.

Vertically it's stuck at the top of the screen. I tried adjusting the "top" variable, but whatever I change it to, it stays at the top of the screen.

string url = "LoginPage.aspx";

StringBuilder sb = new StringBuilder();
sb.Append("<script type = 'text/javascript'> var height=500/((window.top.innerWidth ? window.top.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width) / window.top.screen.availWidth); var width=550/((window.top.innerWidth ? window.top.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width) / window.top.screen.availWidth);");
sb.Append("var left = ((window.top.innerWidth ? window.top.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width) - 550) / 2 / ((window.top.innerWidth ? window.top.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width) / window.top.screen.availWidth) + (window.top.screenLeft !== undefined ? window.top.screenLeft : window.top.screenX);");
sb.Append("var top = ((window.top.innerHeight ? window.top.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height) - 500) / 2 / ((window.top.innerWidth ? window.top.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width) / window.top.screen.availWidth) + (window.top.screenTop !== undefined ? window.top.screenTop : window.top.screenY);");
sb.Append("window.open('");
sb.Append(url);
sb.Append("','_blank','toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no,");
sb.Append("width='+width+',height='+height+',top='+top+',left='+left);");
sb.Append("</script>");

ClientScript.RegisterStartupScript(this.GetType(), "loginscript", sb.ToString());

My solution is taken from: Center a popup window on screen?

William
  • 33
  • 4
  • In line 5 (about height) there is a lot of "top.innerHeight" but later in that line it's all "top.innerWidth". Could it be that those all have to be "top.innerHeight"? – Jos van Weesel Jul 03 '20 at 09:22
  • @SirExotic I get why you would say that, but those are referring to SystemZoom in this post: https://stackoverflow.com/questions/4068373/center-a-popup-window-on-screen And further, as I have tried changing the top variable to other fixed values, the position won't change. So my guess is that the fault isn't in the variable declaration. – William Jul 03 '20 at 09:31

1 Answers1

0

I found the solution. The problem was the variable name "top". I don't know why, but top returned a window object instead. I changed the variable name to "topp", and that worked. I have no idea why, but if anybody knows I'm curious!

William
  • 33
  • 4