How To Center Screen Pop Up Window With JavaScript

Photo of Mike Dalisay
Modified Friday, April 1, 2011
by - @ninjazhai
There was a time when I wanted the contact form of a website to be popped up in another window. I was able to pop-up the window but it was not centered on the screen. For me, it looks better when the window pop up is at the center of you screen. So I found a way to do that. Today we're going to:

1. Create a file with a button and  to trigger the centered pop up window (index.php)
2. Create a file which will serve as the pop up window (contact_form.php)


      <title>How To Center Screen Pop Up Window With JavaScript</title>

<h3>Please click the button below</h3>

<!-- We will use a button to trigger the pop up window -->
<input type='button' value='Contact Us' onclick="showcontactusform()" align="center" /> 

<script type='text/javascript'>
   function showcontactusform() {
      //set the width and height of the 
      //pop up window in pixels
      var width = 500;
      var height = 500;
      //Get the TOP coordinate by
      //getting the 50% of the screen height minus
      //the 50% of the pop up window height
      var top = parseInt((screen.availHeight/2) - (height/2));
      //Get the LEFT coordinate by
      //getting the 50% of the screen width minus
      //the 50% of the pop up window width
      var left = parseInt((screen.availWidth/2) - (width/2));
      //Open the window with the 
      //file to show on the pop up window
      //title of the pop up
      //and other parameter where we will use the
      //values of the variables above'contact_form.php', 
            "Contact The Code Ninja", 
            + left + ",top=" + top + ",screenX=" + left + ",screenY=" + top);    

That's it! :)
For FREE programming tutorials, click the red button below and subscribe! :)
Thanks for the comments!
"First do it, then do it right, then do it better."
~ Addy Osmani
"Talk is cheap. Show me the code."
~ Linus Torvalds
Let's Stay Connected!
g+ r
Android app on Google Play
© 2011-2014 The Code Of A Ninja. All rights reserved. Proudly Powered by Google Blogger. Images, logos, marks or names mentioned herein are the property of their respective owners.