How To Center Popup Window With JavaScript

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 popup is at the center of your screen. So I found a way to do that. Today we’re going to:

1. Create a file with a button and trigger the centered popup window (index.php)

2. Create a file that will serve as the popup window (contact_form.php)

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


<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
      window.open('contact_form.php', 
            "Contact The Code Ninja", 
            "menubar=no,resizable=no,width=500,height=500,scrollbars=yes,left="  
            + left + ",top=" + top + ",screenX=" + left + ",screenY=" + top);    
      }
</script>  
</body>
</html>

That’s it! :)

By Mike Dalisay

I'm Mike Dalisay, a pro web developer since 2010. I love web development. Improving our tutorials and source codes makes me happy. Do you want to suggest an edit to our tutorial? Got something to ask about our source codes? You may use our comments section below or email our team at [email protected]

2 comments

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to top