Simple jQuery Modal Window Tutorial

Written by Kevin Liew on 17 Mar 2009
674,889 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
Luther 15 years ago
hi kevin ... thanks for a wonderful tutorial i really2 need this one.. by the way .. i dont to close my modal by click outside the modal window ... i want it on a close button ... how can i do this?
Reply
Kevin Liew Admin 15 years ago
just put a link or button and assign "close" class to it, and it should do the work. eg:

<a href="#" class="close">Close it!</a>
Reply
tim 15 years ago
I'm using the auto load but would like to limit the popup to the users first visit only. I assume this entails setting a cookie? How would I go about integrating that? Thanks!
Reply
Kevin Liew Admin 15 years ago
Yep, BINGO! So, the steps:

1. Check for cookie (we called it first_visit), if first_visit is not set
2. Show the popup!
3. Set the first_visit cookie

So, basically you need to wrap the modal window code with an IF statement.

For cookie usage: you can refer to one of my tutorials. It has good function to make cookies easy to use.
http://www.queness.com/post/666/weekly-tips-learn-how-to-use-cookie-with-javascript

All the best!
Reply
John 15 years ago
Hello Kevin! This tutorial was great, but the Login Dialog Box, how to you make that kind of ''cut-off'' down in the corner, of your box? I mean the border around the ''Login''
- I would really like to know that, because I'm in need of it hehe :)
Reply
Kevin Liew Admin 15 years ago
It's PNG transparent background image :).. nothing too complicated here. hehe

http://www.queness.com/resources/html/modal/images/login-header.png
Reply
John 15 years ago
Okay, thank you so much, my friend! :D
Reply
Romy R Michael 15 years ago
I h'v a problem to add close button in to model window.... the default close is not working but if i click on mask it ill close .... How do i solve it .... help me
Reply
Kevin Liew Admin 15 years ago
that's weird, as long as you have a class (link) called "close" inside the .window class, it should trigger the close action.

This is the line of code does it:
$('.window .close').click(function (e) {
//Cancel the link behavior
e.preventDefault();
$('#mask, .window').hide();
});
Reply
meem 15 years ago
I don't get it. Why wouldn't one just use $('selector').dialog() with option for modal???
Reply
Kevin Liew Admin 15 years ago
Well, two reasons -
- Learn how to do it with minimal code, your own code.
- A fully customizable and skinable layout. Not just the color, but more complicated styling.
Reply
Pushpesh 15 years ago
Hi Kevin,

thanks for the amazing script...have been using it for quite some time now....very well written and customizable...keep up the good work :)

Best,
Reply
Viktor 15 years ago
Kevin, I did manage to get the popup window to load on page load, and I add a button to close down the popoup. However, after it is closed, the popup window keep on loading (appearing) as if it is looping. Some help please.
Reply
Kevin Liew Admin 14 years ago
I don't think it's looping. I think the page keep refreshing! Make sure you put this to your close button to disable the default behavior of the anchor tag.

return false;
Reply
hubbez 15 years ago
Great work...

I am very new on this. So I cdnt figure out how to make this open onload...I see the code above however I cdnt manage to replace... I want the stick note to open automatically when site loads...

so where does this go:

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

and I should replace with what?

Tnx and regards.
Reply
Kevin Liew Admin 14 years ago
You just need to replace id wit the the id you used in the html code. from above example i named the modal window as "dialog".

$(document).ready(function () {
//id is the ID for the DIV you want to display it as modal window
launchWindow('dialog');
});
Reply
Pat 14 years ago
Hi Kevin, I have followed the tutorial, it's working as expected with a link, but I can't seem to make it load at page load. I see your code (below):

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

But, with your existing code in the <script> section, I'm I just suppose to add the line "launchWindow('dialog');" anywhere in the $(document).ready(function() { sub routine? I tried inserting the launch line under "$(document).ready(function() { " but no dice. Thanks
Reply
Abhilash Sahoo 15 years ago
Very well written. Thank you very much for sharing.
Reply
raza ul mustafa 14 years ago
my question is that how i can connect dilaque box to data base..imagine i have user name and password in data base.how can i set action of this dilaque box to data base in MySQL?
Reply
Kevin Liew Admin 14 years ago
I assume you know server side language and sql etc to do the work (otherwise, it will be really hard). You can use ajax to do the verification, or simply submit the form and redirect to a page.
Reply
tony 14 years ago
hi kevin, this one is an awesome work, however i cant seem to make this one appear on center. Im hoping for your reply, thanks
Reply
Kevin Liew Admin 14 years ago
that's odd, it should be centered by default. Is the demo appear centered to you?
Reply
Panha 14 years ago
When I click the area out side the box, it;s also close the box. How can solve it? I want only click the Close Button to close the box. ^^
Reply
Kevin Liew Admin 14 years ago
Remove this:

//if mask is clicked
$('#mask').click(function () {
$(this).hide();
$('.window').hide();
});
Reply
Tom 14 years ago
This is really odd, but my client uses an Intuit store front for her website and it looks like it does not have a DOCTYPE....weird. Now I got the Modal Window to work in everything except IE which requires a DOCTYPE when using the position style. Do you know of a work around to get this to work in IE with a DOCTYPE? Otherwise the modal window ends up in some weird place and underneath the mask.
Reply