Simple jQuery Modal Window Tutorial

Written by Kevin Liew on 17 Mar 2009
674,883 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
kanishka 14 years ago
its a great help.i can now create and modify modal window according to my requirement.
Reply
Chad 14 years ago
Can you control the positioning of the modal box, so it's not centered? If so, please explain if you could. Thanks for the tutorial.
Reply
Kevin Liew Admin 14 years ago
You may want to change this line manually:
//Set the popup window to center
$(id).css('top', top-value);
$(id).css('left', left-value);
Reply
Sunny 14 years ago
Nice work! while it also works as a full page on smart-phones. I was wondering if/or there is a Mobile version for a modal window like this or similar? or you think the same code can be used for mobile verstions of web pages?
Reply
Kevin Liew Admin 14 years ago
I haven't tried it on mobile, but I think it should work. It's just a simple javascript.
Reply
Sunny 14 years ago
Thanks Kevin. Looking at it closer. you are right. it has to work. Btw, how hard is it to call a different page within the modal? for e.g. <a href="m.yahoo.com" name="modal">Simple Window Modal</a>

How hard would that be? any idea?
Reply
Kevin Liew Admin 14 years ago
Does the popup up show up at all? Did it throw javascript error? If you have an iphone/ipad, try to activate the debugging mode in safari settings.

I tried the demo on iphone, it works. So, what's the issue you're having?
Reply
Kevin Liew Admin 14 years ago
Haha, good to hear that it works!
Reply
Sunny 14 years ago
Yup. like a charm. with proper CSS for it. it looks awesome! Thanks. Now the next task is to show an other page within the modal and pass the value back and forth. :D I'll check on that soon. in the mean-time, if you got some idea, throw it in please. I bet it will help lot others too.
Reply
Kevin Liew Admin 14 years ago
I did that before, basically, you need to setup your modal's content into 3 section, hide the last 2. Not sure if you get what I mean, it's like a 3 steps form.

- Windows modal has 3 section, 1 shown by defaut the rest are hidden
- user did some action to the first section (eg fill in form), then hit next
- if the action is valid, hide the first form, show the second form, and then repeat the same thing....

then you will have a modal windows that capable to display different content. Hope you can understand though. :)
Reply
Mat 14 years ago
Great article and it does work. Any idea why the modal window goes just below the link (take a look at http://www.mat-johnson.net/DKJewelry/collections/x2341.aspx at the bottom under the ring) any idea whats gone wrong?
Reply
Kevin Liew Admin 14 years ago
You need to make sure the CSS file is included.
Reply
traviss 14 years ago
is it possible to get the login screen to open when the page loads?
Reply
Kevin Liew Admin 14 years ago
Please refer to section 4 for auto launch on page load.
Reply
dyte 14 years ago
Hi Kevin,
Thanks for your post, it worked well but I cannot provide its auto launching on page load. As you declare, in section 4, I wrote <body onload="javascript:launchWindow('#dialog')"> or I wrote the function you wrote inside head tags. But it throw that error : Microsoft JScript runtime error: 'launchWindow' is undefined. Any suggestions please?
Reply
Ward 14 years ago
Same problem here..
Any clues on how to fix this?
Reply
Ward 14 years ago
Never mind! Works fine now, missed out on a crucial bit of code.
Would advise anyone to check the link and study source code carefully to make sure you do not miss out on anything:

http://www.queness.com/resources/html/modal/jquery-modal-window2.html
Reply
Tim T. 14 years ago
Hi Kevin,
I really like this tutorial, but I do have a question. I can get everything to work great and as expected, however, once the #mask div and the popup window fills the screen, the #mask div it will not resize when the user resizes the browser window. I was hoping it was a simple CSS issue so I set the width and height of #mask to 100% (html and body are both set to 100% w/h), but it did not work. I'm assuming it has to do with the javascript not continuously measuring the browser width/height. Is there a way to resolve this issue? Thanks a bunch.
Reply
Tim T. 14 years ago
Ha! Just as I sent that, I figured it out:

window.onresize = function(event) {
$('#mask').css({'width':'100%','height':'100%'});
}
Reply
Zain 14 years ago
I tried this function and it doesn't work for me. I'm trying to find a way to automatically resize the mask and the window to the brower window if the user has the browser less than maximized...
Reply
Jeff 14 years ago
How do you hide the scroll bars and still have the modal cover the entire page if you have a tall page?

Adding the following hides the scroll bars but the modal no longer covers the entire page:
$("html, body").css('overflow', 'hidden');

Adding the following should hide the scroll bars and still allow the content to overflow, but it does not hide the scroll bars but the modal still covers the entire page:
$("html, body").css('overflow', 'visible');

The code directly above basically does nothing that I can see.
Reply
Dylan 14 years ago
Kevin,
Great write up and works perfectly. I do have one question. I have a page with multiple buttons or image links that are multiple divs I have created and I want each one of them to have a different story popup using the modal popup. I can't seem to figure out how to get each image to pull up their correct story and not the first images story. Sorry. jquery noob.
Thanks
Reply
Kevin Liew Admin 14 years ago
I think it needs to be AJAX solution otherwise you will have to load all your page content in a single page! Unfortunately, this tutorial wouldn't able to do it.
Reply
shakkeel 14 years ago
Hi, You can have multiple content pop-up by duplicating the #boxes #dialog and renaming it to#boxes #dialog2 in the css and put the content inside <div id="dialog2" class="window"> </div>
link reference:<a href="#dialog2" name="modal"></a>

Hi Kevin, Thanks for the script and I am just an html boy!
Reply
Dylan 14 years ago
Thank you both for the quick replies. Changing the css around did work perfectly. Thanks again.
Reply
Patty 14 years ago
I just wanted to say that this is an AWESOME script. However, I was wondering if you could help me with an issue. I am using the script on several buttons on one screen, and the popup is always in the same spot, which won't work with this page. Is there any way to tie the button with the popup so that it appears near the button? I hope that makes sense. Basically, the issue is that the popup isn't always visible right now, and if I could tie the script to the button, making it always be 100px to the left of the button and about 10px below. Thanks!
Reply
Kevin Liew Admin 14 years ago
This will be a little harder. You will need to caculate the current position of the button. Replace line 28 and 29 with:

//Get the button position and make sure the popup pop under it by adding the button height and extra 10 pixels (you can adjust this 10 pixels offset).
var top = $(this).offset.top + $(this).height() + 10;
var left = $(this).offset.left + $(this).width() + 10;

//Set the popup window to center
$(id).css('top', top);
$(id).css('left', left);

fingers crossed, should work :).
Reply
shakkeel 14 years ago
Hi Kevin, Very helpful and simple to use interface! Thank you!

I am also having the same issue when I click on the footer links the window opens on top of the page and it will not be visible to the user, as the page height is bit high. Can we position it from the bottom of the screen? or on a absolute screen position. so that user can see it clicking from anywhere?

Please let me know your valuable suggestions! Thank you!
Reply
Kevin Liew Admin 14 years ago
Hi Shakeel,

try this top value, basically it grabs the scrollbar value:

var top = $(window).scrollTop() + $(this).height();

$(id).css('top', top);
Reply
Maurice 14 years ago
I thought I'd share that I initially experienced somewhat of the same. In my case, I'd click my link to instruct the modal to appear but if my link was low enough on the page without scrolling further down the modal would appear to render OK. The issue was when I then scrolled further south to a point where my link was now on page near top of window the modal would still appear way up at the top and out of view. I would then have to scroll up to where it was in view. Instead of using your fix as noted (replacing lines 28 and 29...) I added "position:fixed;" to the CSS for the #dialog. This seems to position the modal in the center of page regardless of where I click the link and when the modal and mask appear I don't have to scroll to see it. Again, just thought I'd share since this worked for me. Awesome script btw!
Reply
shakkeel 14 years ago
Hi Kevin, Thanks for the quick reply. Sorry, I don't know how to implement the code, as I am just an html guy and very new to jquery. Can you please help be implement the code you mentioned above?

It will be very helpful if you help me achieve this, as I am using this code for a website for social cause: http://apennyaday.org/test/index.html. If you try clicking the footer link{2 and 3} you can see that the opened modal window is not visible.

Thank you very much!
Reply
Kevin Liew Admin 14 years ago
In the js section, replace 27,28,29 with these few lines:

var top = $(window).scrollTop() + $(this).height() + ($(window).height() / 2 - $(id).width()/2);

//Set the popup window to center
$(id).css('top', top);
$(id).css('left', winW/2-$(id).width()/2);
Reply
Shakkeel 14 years ago
Hi Kevin and Mourice! Thank you very much! Both solutions are working well! Cheers!
Reply
JRajnesh 14 years ago
I h'v a problem to Launch modal window with Javascript .... .... How do i solve it .... help me. Below is the script that i used as same as on the top.

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script>
$(document).ready(function () {
//id is the ID for the DIV you want to display it as modal window
launchWindow(id);
});

//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>

<style>
body {
font-family:verdana;
font-size:15px;
}

a {color:#333; text-decoration:none}
a:hover {color:#ccc; text-decoration:none}

#mask {
position:absolute;
left:0;
top:0;
z-index:9000;
background-color:#000;
display:none;
}

#boxes .window {
position:absolute;
left:0;
top:0;
width:440px;
height:200px;
display:none;
z-index:9999;
padding:20px;
}

#boxes #dialog {
width:375px;
height:203px;
padding:10px;
background-color:#ffffff;
}
</style>

<body>
<h2><a href="http://code.jquery.com/jquery-latest.pack.js"></script> ">Simple jQuery Modal Window Examples from Queness WebBlog</a></h2>

<!-- #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>

</body>
Reply
Kevin Liew Admin 14 years ago
Please download the demo. You missed out big chuck of scripts.
Reply
Bill O 14 years ago
For some reason I get the following error:
--
[13:34:37.852] $(dlgSource).css("display", "none").appendTo("body").dialog is not a function @ http://www.samplesite.com/modules/mod_ecoincart/jcart/js/jcart.js:74

Any ideas why? It almost looks like it's not translating the variables in the javascript.

Bill
Reply
Kevin Liew Admin 14 years ago
The way you use it is incorrect. You can't chain it. It's a function.
Reply
David Bradley 14 years ago
Great script, I've got it working from a link, but having trouble getting it working from onLoad.

I have popped in your bit of script in my script section and replaced ID with the ID of my div:

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

I have re-run my webpage, nothing has happened, but my link still works.

From my knowledge I need to add something into <body onLoad="launchWindow('forgotpassword');">, however, adding this has no effect.

I did some quick debugging and found that launchWindow is undefined.

Sorry for not understanding, but could you give me some further instructions.

Thanks
Reply
Kevin Liew Admin 14 years ago
I assume forgotpassword is an ID for a div. If that's the case, you need to add a hash tag before the id, just like this:

launchWindow('#forgotpassword');
Reply