Basic Modalbox using Jquery

Hello, here i have demonstrated a simple modal popup using JQuery. This modal popup is very basic so u can understand the code flow easily.

Create a new HTML file and and follow these steps..

1. You have to add Jquery Core to at the header of your page.

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>

2. Then u have prepare the html like this.

<a href="#popup" name="modal">Click here to show popup</a>

<div id="popup_item">
 <div id="popup" class="modalbox" style="display:none;">
  <a href="#"class="close"/>Close</a>
  what ever the modal content! what ever the modal content! what ever the modal content! what ever the modal content! what ever the modal content!
 </div>
 <div id="shadow"></div>
</div>

The 1st <a> is the link which will active the modal popup and the <div id=”popup_item”> will be the modal popup.

3. Now You have to add the Jquery code which will make your modalbox/popup functional

<script>

$(document).ready(function() {    

 $('a[name=modal]').click(function(e) {

  e.preventDefault();
  var id = $(this).attr('href');
  var shadowHeight = $(document).height();
  var shadowWidth = $(window).width();
  $('#shadow').css({'width':shadowWidth,'height':shadowHeight});

  $('#shadow').fadeIn('fast');    

  var winH = $(window).height();
  var winW = $(window).width();

  $(id).css('top',  winH/2-$(id).height()/2-100);
  $(id).css('left', winW/2-$(id).width()/2);

  $(id).fadeIn('slow'); 

 });

 $('#popup_item #shadow').click(function () {
  $(this).hide();
  $('#shadow').fadeOut('slow');    
  $('.modalbox').hide();
 });        

 $('#popup_item .close').click(function (e) {
  e.preventDefault();
  $('#shadow').fadeOut('slow');    
  $('.modalbox').hide();
 });        

});

</script>

4. Finally the CSS,

<style>
#shadow {
 display:none;
 position:fixed;
 left:0;
 top:0;
 z-index:9000;
 background-color:#000;
 opacity: 0.8;
}

#popup_item .modalbox {
 position:fixed;
 left:0;
 top:0;
 display:none;
 z-index:9999;
}

#popup_item .close{
 position:absolute;
 background-color:#fff;
 border:1px solid red;
 color:red;
 padding:2px 5px;
 right:-10px;
 text-decoration:none;
 top:-10px;    
}

#popup_item #popup {
 width:400px;
 height:auto;
 padding:10px;
 background-color:#fff;
}
</style>

Now run the html file and enjoy.