Sunday, October 20, 2013

Popups using Javascript and CSS

In this post, I'm writing about an interesting way of displaying popups using javascript and css.

These popups do not show up in a new window, but rather in the same page as a different box. You might have seen these kind of popups while logging in or during display of your profile details in various social networking sites or email websites like gmail.

The idea here is to use css and div to display a box which embeds a separate html form of its own.
Lets first create a the form elements for login:

<div id="popupbox"> 
<form name="login" action="" method="post">
<div id="centertag">Username:</div>
<div id="centertag"><input name="username" size="14" /></div>
<div id="centertag">Password:</div>
<div id="centertag"><input name="password" type="password" size="14" /></div>
<a href="javascript:document.form.submit();"">
<div id="centertag">
        <span id="squares">
             <div id="1"><span>Login</span></div>    
        </span>
</div>
</a>
</form>
<br />
</div> 

The centertag style is used center align the login fields. The squares style is used to show the square box substitute for button (showing 'Login'). However, the style to look for is the 'popupbox' which will create the login popup box. Note that we have used absolute positioning to place the login box in the required position.

Lets take a look at the css styles:

<style type="text/css">
  #popupbox{
      margin: 0; 
      margin-left: 40%; 
      margin-right: 40%;
      margin-top: 50px; 
      padding-top: 10px; 
      width: 20%; 
      height: 150px; 
      position: absolute; 
      background: #FFFFFF; 
      border: solid #68BEC9 1px; 
      z-index: 9; 
      font-family: arial; 
      visibility: hidden; 
  }
  
  #centertag{
      text-align: center;
      margin-bottom: 5px; 
  }
 
  #squares div {
      display: block;
      float: left;

      width: 112px;
      height: 30px;
      line-height: 30px;
      background: #E0E0E0;
      text-align: center;
      font-family: Arial, Helvetica, sans-serif;
      border: solid #68BEC9 1px; 
      margin-right: 5px; 
  }
  span {
      display: inline-block;
      vertical-align: middle;
      line-height: normal;      
      margin-top: 5px;
  }
 </style>


The last part is the javascript function to show this login popup.

<script language="JavaScript" type="text/javascript">
  function login(showhide){
    if(showhide == "show"){
        document.getElementById('popupbox').style.visibility="visible";
    }
  }
</script>

Invoking the above function will display the login popup as shown below:

<a href="javascript:login('show');">login</a></p>

No comments:

Post a Comment