Tuesday, August 2, 2011

Create custom popup window

Here's the easiest way to create popup window using javascript function. before you use this code i assume that you have already created html page and you are better aware of <head></head> tag.


Copy this code in the <head></head> section of you html page.

<head runat="server">
  <title>Custom LightBox example</title>
  <script type="text/javascript">
  function showBox()
  {
    var width = document.documentElement.clientWidth + document.documentElement.scrollLeft;
    var layer = document.createElement('div');
    layer.style.zIndex = 2;
    layer.id = 'layer';
    layer.style.position = 'absolute';
    layer.style.top = '0px';
    layer.style.left = '0px';
    layer.style.height = document.documentElement.scrollHeight + 'px';
    layer.style.width = width + 'px';
    layer.style.backgroundColor = 'black';
    layer.style.opacity = '.6';
    layer.style.filter += ("progid:DXImageTransform.Microsoft.Alpha(opacity=60)");
    document.body.appendChild(layer);
  
    var div = document.createElement('div');
    div.style.zIndex = 3;
    div.id = 'box';
    div.style.position ='absolute';
    div.style.top = '200px';
    div.style.left = (width / 2) - (400 / 2) + 'px';
    div.style.height = '100px';
    div.style.width = '400px';
    div.style.backgroundColor = 'white';
    div.style.border = '2px solid silver';
    div.style.padding = '20px';
    document.body.appendChild(div);
  
    var p = document.createElement('p');
    p.innerHTML = '<b>This is my first custom dialog box</b><br/>';
    div.appendChild(p);
  
    var a = document.createElement('a');
    a.innerHTML = 'Close window';
    a.href = 'javascript:void(0)';
    a.onclick = function()
    {
      document.body.removeChild(document.getElementById('layer'));
      document.body.removeChild(document.getElementById('box'));
    };
    
    div.appendChild(a);
  }
  </script>  
</head>

Now paste the below code in <body></body> section.

<body>

  <a href="javascript:void(showBox())">Toggle box</a>
    
</body>


You are done, run the page and click on Toggle box link
You will see the below screen.


Note you can customise the popup by changing the div style:

 div.style.zIndex = 3;
div.id = 'box';
div.style.position ='fixed';
div.style.top = '300px';
div.style.left = (width / 2) - (100 / 2) + 'px';
div.style.height = '300px';
div.style.width = '400px';
div.style.backgroundColor = 'yellow';
div.style.border = '2px solid red';
div.style.padding = '20px';

Hope you found this article useful.