jQuery: modal window example

Modal windows are surely one of the most interesting things that you can build with jQuery. In this post I'm going to show you how to create one of those modal windows, plus adding an overlay effect when the window is showed. Most of the heavy-lifting is done by CSS, while jQuery simply adds and shows the element created from scratch. Here's our HTML structure that we're going to create with jQuery:

<div class="modal">
 <div class="modal-close">
  <a href="#" class="close">Close</a>
 </div>
 <div class="modal-content">
 
  <!--mixed content here-->
  
  <img />
 
 </div>
</div>

Some CSS rules for the modal window and the overlay element:

div.modal {
 width: 600px;
 height: 400px;
 position: absolute;
 top: 50%;
 left: 50%;
 margin: -200px 0 0 -300px;
 border-bottom: 5px solid #2b2b36;
}

div.modal-close {
 width: 200px;
 height: 60px;
 background: url(tab-modal.gif) no-repeat;
 float: right;
 position: relative;
}

div.modal-close a {
 display: block;
 width: 46px;
 height: 46px;
 text-indent: -1000em;
 background: url(close-modal.gif) no-repeat;
 position: absolute;
 top: 6px;
 right: 10px;
}

div.modal-content {
 background: #ffa;
 height: 308px;
 padding: 1em;
 clear: both;
 margin: 0;
 position: relative;
}

div.modal-content img {
 width: 400px;
 height: 280px;
 display: block;
 position: absolute;
 top: 50%;
 left: 50%;
 margin: -140px 0 0 -200px;
}

#overlay {
 position: absolute;
 top: 0;
 left: 0;
 background: #ffc;
}

Finally, jQuery:

var modal = '<div class="modal">' +
            '<div class="modal-close">' +
            '<a href="#" class="close">Close</a>' +
            '</div>' +
            '<div class="modal-content">'+
            '<img src="path/1.jpg" />' +
            '</div>' +
            '</div>';
var overlay = '<div id="overlay"/>';
            
$(document).ready(function() {

  $('#run').click(function(e) {

  $(overlay).css({
    width: $(document).width(),
    height: $(document).height(),
    opacity: '0.5'
  }).prependTo('body');
  
  $(modal).appendTo('html');
  
  e.preventDefault();
  
  });
  
  $('a.close').live('click', function(e) {
  
  
    var parent = $(this).parent().parent().remove();
    
    $('#overlay').remove();
    
    e.preventDefault();
  
  
  });
  
  

});

The overlay element will be put just before body, thus creating the effect of a semi-transparent layer. Instead, the modal window must be put over this layer, so we append it to the html element. Then we use the live() method to attach a click event to the newly created closing buttons that will remove both the overlay and the modal window. You can see a demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.