Simple jQuery Modal Window Tutorial

Written by Kevin Liew on 17 Mar 2009
674,839 Views • Tutorials

Introduction

In this tutorial, I'm going to share how to create a simple modal window with jQuery. I like jQuery, it makes everything so simple and so easy. In case you don't know what's modal window. You can click here. That's an example of a modal window.

In this website, I'm using facebox (inspiration from facebook). Others, such as lightbox, thickbox, multibox, litebox...... it's too many of them and they all are having different features.

Right, let's start, this example will show you how to create a modal window that will display the content of a DIV #ID.

My objectives are:

  • Able to search the whole html document for A tag NAME="modal" attribute, so when users click on it, it will display the content of DIV #ID in the HREF attribute in Modal Window.
  • A mask that will fill the whole screen.
  • Modal windows that is simple and easy to modify.
Advertisement

1. HTML code and A tag attributes

<!-- #dialog is the id of a DIV defined in the code below -->
<a href="#dialog" name="modal">Simple Modal Window</a>

<div id="boxes">

	
	<!-- #customize your modal window here -->

	<div id="dialog" class="window">
		<b>Testing of Modal Window</b> | 
		
		<!-- close button is defined as close class -->
		<a href="#" class="close">Close it</a>

	</div>

	
	<!-- Do not remove div#mask, because you'll need it to fill the whole screen -->	
 	<div id="mask"></div>
</div>

2. CSS code

<style>

/* Z-index of #mask must lower than #boxes .window */
#mask {
  position:absolute;
  z-index:9000;
  background-color:#000;
  display:none;
}
  
#boxes .window {
  position:fixed;
  width:440px;
  height:200px;
  display:none;
  z-index:9999;
  padding:20px;
}


/* Customize your modal window here, you can add background image too */
#boxes #dialog {
  width:375px; 
  height:203px;
}
</style>

3. Javascript

<script>

$(document).ready(function() {	

	//select all the a tag with name equal to modal
	$('a[name=modal]').click(function(e) {
		//Cancel the link behavior
		e.preventDefault();
		//Get the A tag
		var id = $(this).attr('href');
	
		//Get the screen height and width
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();
	
		//Set height and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});
		
		//transition effect		
		$('#mask').fadeIn(1000);	
		$('#mask').fadeTo("slow",0.8);	
	
		//Get the window height and width
		var winH = $(window).height();
		var winW = $(window).width();
              
		//Set the popup window to center
		$(id).css('top',  winH/2-$(id).height()/2);
		$(id).css('left', winW/2-$(id).width()/2);
	
		//transition effect
		$(id).fadeIn(2000); 
	
	});
	
	//if close button is clicked
	$('.window .close').click(function (e) {
		//Cancel the link behavior
		e.preventDefault();
		$('#mask, .window').hide();
	});		
	
	//if mask is clicked
	$('#mask').click(function () {
		$(this).hide();
		$('.window').hide();
	});			
	
});

</script>

It's very straight forward and easy to understand. Remember, you need to include jQuery framework.

Demonstration Download

4. Launch modal window with Javascript

Due to popular demand :), I have an example for it. The concept is simple. I wrapped the modal window script inside a function, and then you will able to call the modal window using javascript function call.

Yes, you will able to load the modal window on page load as well :)

$(document).ready(function () {
  //id is the ID for the DIV you want to display it as modal window
  launchWindow(id); 
});

Demonstration

And, if you want to close the modal window on key press, any keys you want, you can add the following function.

$(document).keyup(function(e) {
  if(e.keyCode == 13) {
    $('#mask').hide();
    $('.window').hide();
  }
});

Use Cookie on First Load

Another popular demand from readers and this is how you do it. You need two functions (createCookie and readCookie) from this post about web cookies

$(document).ready(function() {
//if the cookie hasLaunch is not set, then show the modal window
if (!readCookie('hasLaunch')) {
	//launch it
	launchWindow('#dialog1');		
	//then set the cookie, so next time the modal won't be displaying again.
	createCookie('hasLaunch', 1, 365);
}

});

Demonstration

Recalculate the Position of Modal window and mask on window resize

Don't know how I missed it, this is the code that reposition the modal window and recalculate the dimension of mask if user resized the windows.

$(document).ready(function () {
$(window).resize(function () {
 
 		var box = $('#boxes .window');
 
        //Get the screen height and width
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();
      
        //Set height and width to mask to fill up the whole screen
        $('#mask').css({'width':maskWidth,'height':maskHeight});
               
        //Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();
 
        //Set the popup window to center
        box.css('top',  winH/2 - box.height()/2);
        box.css('left', winW/2 - box.width()/2);
 
});

});
I think I should make another post about modal window. :)

5. Conclusion

Yes, that's all you need to make a simple jquery modal window. In this tutorial, it shown you the concept of how to display DIV content inside a modal window. However, you can further develop it to accept a link and display it in an iFrame and image gallery.

For those who's looking for a fully customizable Modal Window, you can try my method, if you have any other questions, please let me know. Thanks for reading.

Update

29-2-2012: - Fixed auto resize, change modal window's position from absolute to fixed.

 

22-5-2009: - Added a new section "Activate modal window with Javascript"

16-4-2009: - If you prefer this article in Portuguese, please visit Simple jQuery Modal Window in Portuguese by Maujor

27-3-09: - Added e.preventDefault() to link to launch the modal window.
- Changed css position to fixed, so that the modal window also fixed to center. - Changed var winH = $(window).height(); to var winH = $(window).height();

24 Mar 09:
- Added e.preventDefault() to cancel the anchor link effect, we can also able to cancel it by removing the href attribute.
- Changed var winH = $(window).height(); to var winH = $(document).height();

Demo Download
Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

797 comments
leonardo 14 years ago
Really good, thanks for your help
Reply
Nika 14 years ago
Nice code! I've been looking for a solution like yours.

I only have one problem, if you can advise:
I have some collapsible items in my modal window (my #dialog div is created dynamically from XML and contains collapsible divs). So, whenever I expand a few of them, the height of the #dialog div is changing. At some point, my #dialog div becomes longer than the mask (mask is not resizing). How can I fix that? I tried to add ".click" listener to my link when I expand the item and resize the #mask, but it only works after I click it next time to collapse the item (but this messes up the height of the document: it remains too long even when I collapse back all the items).

Do you have any ideas?
Reply
Kevin Liew Admin 14 years ago
You can set the mask dimension with this:

//Get the screen height and width
var maskHeight = $(document).height();
var maskWidth = $(window).width();

//Set height and width to mask to fill up the whole screen
$('#mask').css({'width':maskWidth,'height':maskHeight});

I assume you can attach this in your expand/collapse link, so whenever the user clicks on it, it always recalculate the mask dimension.
Reply
Nika 14 years ago
Thanks for trying to help, but I couldn't make it work so far.. Can you please take a look at http://sammyskitchen-rehoboth.com/testing/pages/menu.html?page=2
I tried to put the mask dimensions in different places, but I guess not in the right ones :)
Reply
Miguel 14 years ago
Thanks for your contribution. Really good!!
Reply
M Tahir 14 years ago
Its really nice, good work buddy :)
Reply
puneet 14 years ago
nice I want to try !
hw Can we pass data via $POST_GET to new window ?
Reply
Christopher Robb 14 years ago
Thanks for taking the time to create and package the example in such a clean and concise manner. Nice work. I'm sure that it is well appreciated
Reply
Andreas 14 years ago
Is it possible to add scrollbars, if the content is longer then the modal window?
Reply
Kevin Liew Admin 14 years ago
You can set the CSS of this:
#boxes #dialog {
........
overflow: auto;
}
Reply
andrew 14 years ago
I like this, but is there any way to do this on page load and not on a click event? Every single one of these I look at assumes that people are clicking on an item like a photo or div element. Yet a lot of sites now days are popping up modal overlays to encourage site registration on Ready, not when they click.
Reply
Jean 14 years ago
Thanks for the awesome pop up.
I just have some problems with the auto pop up option with the cookie, and have been reading the previous comments and also the weekly tips with the java script and actually have no idea how to work with it. I also tried the code done by vanessa and for some reason I'm keep getting errors. It'll be great if you could give me some insight on how to solve this.

Thanks <3.
Reply
Kevin Liew Admin 14 years ago
Hi Jean, sorry for the late reply. I have made a quick demo for you and updated the article to include cookie.
http://www.queness.com/resources/html/modal/jquery-modal-window-cookie.html
Reply
Jean 14 years ago
Thank you so much! It worked perfectly <3
Reply
jn7_85 14 years ago
Hi Kevin. Thank you for sharing this. The modal window looks awesome! :). I am only having issues with the animation. Is there a way to make the fade animation faster? i tried going through the java script and changed slow to fast but that has not really addressed the issue. Also, i tried putting icolorpicker into the modals but it doesn't seem to be working. any idea why this is happening? again, thank you for all your great work. :)
Reply
Kevin Liew Admin 14 years ago
You can change mask's transition effect in line 20 and 21.
Modal window - line 32.
Reply
Sam 14 years ago
This code helps me alot... Thank you...
Reply
ppp 14 years ago
Thanks! Very useful.
Reply
karl 14 years ago
Thank you for such a clear explanation! I've been trying to find a concise example such as yours, that is both easy to implement and easy to modify.

Could you offer some advice on how to insert a "close" graphic "X" button in the top right hand corner, and more specifically, how does one link the graphic to the keyup function script?
Reply
Kevin Liew Admin 14 years ago
Use this:

#boxes { position: relative }

Then create this and put it inside #boxes.
<a href="#" class="close" id="btn-close">Close</a>

Then, style it with CSS. You can adjust the pos accordingly
#btn-close { position:absolute; right:0; top:0 }
Reply
karl 14 years ago
Thanks Kevin!

One more question: I am trying to create a list within the dialog box, but the bullets are not visible:

<div id="boxes" position: relative>
<div id="dialog" class="window">
<ul>
<li>Simple Modal Window1 Simple Modal Window1 Simple Modal Window1</li>
<li>Simple Modal Window1 Simple Modal Window1 Simple Modal Window1</li>
</ul>
<a href="#" class="close" id="btn-close"><img src="resources/modalwindow/x.png"></a>
</div>

with <ul> { list-style-type: decimal; padding: 0em; margin: 0em; }

but I'm not entirely sure if <ul> and/or <li> is supposed to be associated with a particular # ?

Reply
Kevin Liew Admin 14 years ago
that's interesting, my css has nothing to do with the list. You can also try:
li {list-style-type: decimal}
Reply