Simple jQuery Modal Window Tutorial

Written by Kevin Liew on 17 Mar 2009
674,853 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
Brian Merrill 14 years ago
Hello, The modal window is working perfectly but in IE8 I am getting a horizontal scroll bar when the modal window is launched. Is there a way to fix? Thank you, B
Reply
Kevin Liew Admin 14 years ago
hmm, that's weird, I have tested it on IE8 before. Was it the mask causing the horizontal scrollbar?
Reply
JesseD 14 years ago
This tutorial doesn't seem to work in Safari.
Reply
JesseD 14 years ago
Sorry I got to rephrase that, the Demo doesn't work in the new Safari for windows due to the Jquery library source isn't downloading. Great tutorial!
Reply
Kevin Liew Admin 14 years ago
hmm, I tested it with safari on mac and window, it works fine.
Reply
Munir 14 years ago
Thanks for this man, It helped me to finish my work :)
Reply
Todd Fooshee 14 years ago
Alright first of all, thanks for the script. It's great and really customizable, which I appreciate.

I did have one thing I was trying to do with it though that I can't seem to figure out.

On a particular page on this site I'm designing, I have some links that are at various locations down the page. You have to scroll for a majority of them. The problem is, as you scroll and click one of the links, the box comes up way back up at the top of the page. So what I'm wondering is, is there a way to change that so that the box always pops up in the middle of the screen no matter where you're scrolled on the page?

Thanks!
Reply
Kevin Liew Admin 14 years ago
Try to change .window position:absolute to position:fixed
Reply
Dan 14 years ago
This works great apart from forms. If I put form elements within the modal form and inspect them with firebug, it changes them to

<form name='myform'></form>
<input type='text' name='textbox'>

For some reason the form elements get placed outside of the form. Same form works fine outside of the modal box and inspects fine with firebug
Reply
Kevin Liew Admin 14 years ago
Weird. Have you try to submit the form?
Reply
Chadwick 14 years ago
Hi, I used this one on my site but I have a problem, everytime I clicked my images on the gallery. the popup window, on the first click, it disaligns and if you click the image again, it now became centered.Giv me some help thanks. here is the link http://anonymousmind.site40.net/veryint/
Reply
Kevin Liew Admin 14 years ago
Hi Chadwick, Im glad to see how you try to expand this script into a popup gallery. But I think it's the size of the images causing the calculation of the modal position incorrect. If you have to do this, I would recommend fancybox, it's a better solution to meet your need. http://fancyapps.com/fancybox/
Reply
Saltspringer 14 years ago
Works nicely, but the Simple Window Modal doesn't open in the middle of the window if you have a loooong window - it opens way up at the top. Any way to fix this.

Thank you for making this.
Reply
Kevin Liew Admin 14 years ago
You can fix it by changing:

#boxes .window {
position:absolute;

to

#boxes .window {
position:fixed;
Reply
AMit 14 years ago
Hi,
We have created a JQUERY modal window. we have a left navigation bar. Once user clicks on that the right area should get populated with a tabular data from Server. To pull this data I am using AJAX in spring 3.0 framework. Controller sends me a model view which is a jsp file. upon receiving this jsp file I am injecting the content into a div id. now clicking on the anchor tag for the modal window is not working. I suspect it is not finding the a[name=modal].click event as i have an alert inside it. My Ajax req is
$(document).ready(function(){
$.ajax({
type: "POST",
url: "getAllMPs.do?periodType="+periodType,
success:function(response){
$.globalEval(response)
document.getElementById("main_outer").innerHTML = response;
}
});
});
Kindly help me in finding out wher am i going wrong. and the possible solution to it
Thanks
Reply
Kevin Liew Admin 14 years ago
from the code you pasted above, I can see there is a missing ; in this line:
$.globalEval(response)

A few suggestions for debugging:
1. use firebug or chrome console to see javascript error.
2. remove your script, and make sure the modal window is working first.
3. if the modal works after the removal of your script, then it indicates there is something wrong with yours script.
Reply
Sam 14 years ago
Can you please include a javascript activation example?
I tried that javascript snippet you included but it doesn't work for me.

Thanks
Reply
Kevin Liew Admin 14 years ago
Zain 14 years ago
HI, I have the popups working on my website, but I am wondering is there anyway to call the popup directly using the hashtag?

For example let's say i have a link on an external site which links to:

www.mysite.com/test.html#dialog2

so when you click on that link it takes you to the website and on page load directly pops up the dialog2.
Another link could take to test.html#dialog3 and that pops up on page load.

Is this possible?

Thanks for your help in advance!
Reply
Zain 14 years ago
EDIT: I got it to work thanks! Here's the code I used:

if(window.location.href.indexOf("#dialog2") != -1)
{
launchWindow('#dialog2');
} else if (window.location.href.indexOf("#dialog3") != -1)
{
launchWindow('#dialog3');
}
else if (window.location.href.indexOf("#dialog4") != -1)
{
launchWindow('#dialog4');
}
else if (window.location.href.indexOf("#dialog5") != -1)
{
launchWindow('#dialog5');
}
else if (window.location.href.indexOf("#dialog6") != -1)
{
launchWindow('#dialog6');
}

Can someone tell me if this is a correct use? I tried it in IE, Firefox and Chrome and it works in all. Tried different PC's too. It works, but just wondering of correct syntax.
Reply
Kevin Liew Admin 14 years ago
Just a suggestion, I haven't tested this code but I think it might work:

var hash = window.location.hash;

if (hash) {
try {
launchWindow(hash);
} catch(e) {
//error message, just leave it blank
}
}


and oh, you can use window.location.hash to get the hash tag :)
Reply
Chris 14 years ago
@Zain: Where did you put the code that you posted in your comment? I've tried to copy/paste it into the script section, but it doesn't work for me. Some help, please? Thanks.
Reply
hi 14 years ago
hi i try to do the same thing as Zain but it does not work.. Where do i put the code?
Reply
Kevin Liew Admin 14 years ago
You should put it on document load.

$(document).ready(function () {

// Zain Code here

});
Reply
prash saxen 14 years ago
Nice script ...Can you please help me ?

Is it possible to open popup window after loading of all content of the page .. i mean like body onload ?/
Reply
Kevin Liew Admin 14 years ago
Please read section 4 of the tutorial.
Reply
Tim 14 years ago
Trying to simply recreate your sample - my mask does not cover the HTML link 'Simple Model Window'. Any suggestions?
Reply
Kevin Liew Admin 14 years ago
Did you download the demo?
Reply
Tim 14 years ago
Yes I did - I found that if I add a TOP:0 and LEFT: 0 to the #Mask CSS definition, the mask then covers the HTML link.
Reply
Mary Mac 14 years ago
Why is it that when I put two "modals" in one div the "close" doesn't work on the second one?
Reply