Simple jQuery Modal Window Tutorial

Written by Kevin Liew on 17 Mar 2009
674,847 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
Victoria 14 years ago
Thank you for this, it's exactly what I need!

I am having an issue though. When my page is first loaded, the modal div is visible. It isn't until the close button is clicked that it disappears and looks like I assume it's supposed to look on load. I do have a bit of an odd setup, I suppose, so something may be interfering. I'm using Wordpress and my posts are being loaded in table data cells (the ecommerce plugin I'm using requires this, sadly). When the image is clicked, that's when the modal div is supposed to be loaded above everything. I'm still working out the kinks - I don't expect you to help me with things unrelated to your post, just thought it might be useful information. :] http://www.soulabstract.com/product/
Reply
Kevin Liew Admin 14 years ago
Hi Victoria,

I went to your website, but I can't see the issue you mentioned above. I tested it with Chrome & Firefox. So, i use the link above, on first load, i can't see the modal div, everything looks alright. Then I click on the product image, the modal div popup and I was able to close the modal. Everything looks okay to me.
Reply
Mary Mac 14 years ago
When I put a second "modal" on my page the close button doesn't work. Do I need to put it in it's own div?
Reply
Abhay 14 years ago
Thanks much for this wonderful stuff! Great tutorial! Kudos to you! :-)
Reply
Mary Mac 14 years ago
Never mind. I figured it out. Not enough coffee!
Reply
Kelsy Franklin 14 years ago
Hey Everyone. I'm using an iframe in the Simple Window Modal, but the mask stopped working the moment I put the iframe in. Everything works beautifully, but I would prefer to the black background mask show up behind the iframe.

Any ideas on why this is happening or how I can resolve this? Thank you!!!
Reply
astha 14 years ago
how can i refer to the 'dialog' (id of div tag) without using any link .means i want to open the pop up window just after clicking the button in jQuery without clicking on any furthur link.
Reply
Kevin Liew Admin 14 years ago
You need to give the button a class or id, then you change it here (line 6):

$('button#id').click(function(e) {
Reply
minsara 14 years ago
Tnx alot........It worked. Looked out for the same thing....
Reply
Yasser 14 years ago
hey man! THANK YOU SO MUCH ! this is an amazing script :)

However, the screen resize is not working. it is giving me an error that the the "id" is null .. I think I am using it wrong. can you please tell me how can I use it correctly ?
Reply
Matt Mason 14 years ago
I have the same problem as you Yasser... Any ideas?
Reply
Kevin Liew Admin 14 years ago
Hey guys, sorry for the bug. I have fixed it and updated the tutorial. You can download the demo for the latest update. I have fixed the auto resize and also set the modal window's position to fixed position to make sure it always display in the center.
Reply
Paul 14 years ago
I have the problem where I need the modal window to popup in the middle of the screen, but if I set it to fixed, then I cannot scroll the window on a smaller resolution.
Reply
Jason McIntosh 14 years ago
I also have a long window and have changed #boxes .window to a fixed position, but it's still scrolling upward.

Here's a link to my page (The first "read more" is working, make sure to scroll a bit):
http://jmcintosh.aisites.com/allison/history.html

Reply
Kevin Liew Admin 14 years ago
Please download the latest version. Should fix your issue.
Reply
Jason 14 years ago
Thanks for that. It looks as though I have a conflict with another scrolling script on the page. Appreciate your response.
Reply
morro 14 years ago
hi! nice script! is there a way to target the modal window to the parent element? i´m using it in an iframe and it fills the iframe only, can you help me? thanks!!
Reply
Matt Sigley 14 years ago
Kevin, I adapted your work here into a simple jquery plugin. I can email you my first revision of it if you are interested.
Reply
Kevin Liew Admin 14 years ago
That's cool Matt, you can send it to queness[at]queness[dot].com
Reply
nobody 14 years ago
This code is incredibly sloppy. Trailing white space everywhere, spaces instead of tabs for indentation, OSX crap files included in the .zip, redundant variables in the javascript, completely unhelpful comments that merely state the obvious, inconsistent indentation in the css...

On the whole it's all very unprofessional, I'm amazed you manage to get anything done at all. This just reinforces the stereotype that mac users are hipster idiots who're in it for the image and think that writing HTML is the same as programming.
Reply
Kevin Liew Admin 14 years ago
I hope you will understand, this tutorial is dated Mar 2009, my first tutorial and I was learning jQuery back then. I didn't expect queness will grow to this size. For your comment of me being unprofessional, I wasn't trying to be a professional in the first place, it's just a blog that shares what I have learned. I might not be as hardcore programmer/web developer as you are, but I do appreciate your comment and will try to improve and release higher quality tutorials.

For the Mac user part, it seems to be you're trying to start one of those never-ending pc vs mac debate, get over it. It's unprofessional ;)
Reply