Simple jQuery Modal Window Tutorial

Written by Kevin Liew on 17 Mar 2009
674,907 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
Jeremie 15 years ago
Hi Kevin, Thanks for this tutorial that works very well... except if your page is inside an iframe and that you don't have access to the parent. In that case, the modale is not centering properly vertically. Thanks anyway :)
Reply
Kevin Liew Admin 15 years ago
interesting implementation. i dont think other modal window can do that as well.
Reply
x-men 15 years ago
how to used as body onload ?
Reply
Kevin Liew Admin 15 years ago
Please check section 4.
Reply
x-ramen 15 years ago
oh.. i see. i do it like this

<script>
$(function(){
// jQuery UI Dialog

$('#dialog').dialog({
autoOpen: true, <---- i set here
width: 420,
modal: true,
bla..bla..bla..
</script>

sir, i recommend you to use auto responder, bcoz i din't know that u are reply my comment. btw thank!
Reply
Metroprog 15 years ago
Hey Kevin, thanks for the great tutorial !
I was having a slight problem when I clicked close or clicked on the mask to hide the box, sometimes the mask reappeared right after closing it, it mostly happened when I closed it quickly. Now I've fixed this issue by adding like .hide(200); to both the mask and the dialog box.
The other thing I'm trying to figure out is how can I let the user interact with buttons inside the dialog without closing it. For example I'm trying to make a contact us form in the dialog, any button I place in the dialog box is making the window close on click. Thanks for your help
Reply
Kevin Liew Admin 15 years ago
that's strange... you should able to make a button inside the modal window. only link or button with .close class will close the modal window.
Reply
Metroprog 15 years ago
Actually I found the issue, the other button I have in the dialog is an asp.net button doing page postback, and that's making the dialog close, I tried to add an ajax update panel inside the jquery dialog to prevent a postback, but that doesn't work, looks like ajax is conflicting with jquery. Any ideas ?
Reply
Undye 15 years ago
Thanx a milion man ! you're a life saver - it was the best tutorial I found on the whole WWW ! You rule !
Reply
Angel 15 years ago
wow Great.!! But i have a question, my back page is not hidding, it show me the modal div, but everything is not locked like a "modal behavior" :S
Reply
Ryan Michael Reyes 15 years ago
after a few tries, i managed to use this one... and had the same prob as yours... but i resolved it by NOT MISSING the div with the mask ID... ^___^
Reply
angel 15 years ago
Hi..!! Tnks, this is awesome, but i have a prblem..! my back page is not getting black when my window is showing ..!! :S what im doing wrong
Reply
Kevin Liew Admin 15 years ago
make sure you have this tag: <div id="mask"></div>, if yes, does the demo work on your browser? if yes, you must have missed something. if no, please let me know.
Reply
Angel 15 years ago
Ohh!! tnks!!! i didnt have this tag <div id="mask"></div> !! geniuss!!
Reply
Hari 15 years ago
Couldn't make it load automatically. Can you include the auto load script with your demo script for download?
Reply
Carlos 15 years ago
This was awesome. Thank you very much for this tutorial.
The code was really simple and easy to follow. :)

I just have one tip for those of you who are interested in having the modal window always centered on screen.
Just have to make a small change on the stylesheet:

CHANGE THIS: #boxes .window { position:absolute; } to ---> #boxes .window { position: fixed; }

i dont't know if this is so obvious, but sure spent some time trying to find a fancy way to do this with jquery, and turns out it was way easier with just css. :)

THANK YOU AGAIN!

I'll be checking this blog
Reply
Bao 15 years ago
Hi, this does not work in IE, I have a flash and now whenever our company has any events, i want to use this code to display event. However, with FF and GC, it works well, but with IE, I think the z-index does not work, its underneath the flash file. How can I fix it, thax guys
Reply
Kevin Liew Admin 15 years ago
I think you need to set flash wmode to transparent.
Reply
Eelco Kamps 15 years ago
Hello all,

This is a great script. Love it! Customized it in a separate html and all worked fatasticly. Until I copy pasted all the parts of the script in my own page. Suddenly nothing happend. No modal-window. I checked a lot of things, including things like z-index, but I can't find the cause.
One thing that is obviously different is that, in the separate html the starting link displays left, but in my own page, even directly below the bodytag it centers. I created a new css div-container to correct this, but the link now on the left, it didn't help. I'm quite new to all this and I have no clue why directly copying and pasting shouldn't work. Do you have any idea?

My gratitude on forhand, Eelco.
Reply
atlos 15 years ago
I had problem with IE7 + Win7.
Div #mask did not show properly.
Fix: $('#mask').css({'width':maskWidth,'height':maskHeight,'top':0,'left':0});
Reply
Mark F 15 years ago
Is there a reason (compatiblity?) why the mask is sized manually vs just setting the height and width to 100%? I've tried the 100% mask and tested it in IE7, IE9, Firefox5 and Chrome. Also this allows users to resize the live window while keeping the mask covering the whole screen.
Reply
Ian T. 15 years ago
Kev, you are the man!! After much trial and tribulation, I managed to use your simple Modal Window for showing Video in it using dynamic information from my database and using a flash player. I spent days trying out video/Jquery ready modal examples, and none of them did what I wanted them to do. Because of your brilliant script I was able to bespoke it to suit my purposes. Brilliant!!
Reply