Simple jQuery Modal Window Tutorial

Written by Kevin Liew on 17 Mar 2009
674,863 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
Jasonlkjfds 14 years ago

Hi, great tutorial, simple easy to understand code. I have this working on a website I'm working, using only the simple modal and adding my custom form to it. My issue is that I can't seem to change the size of the modal. I tried changing the #dialog .window height and width but it does not affect the modal's size. Any suggestions?
Reply
Kevin Liew Admin 14 years ago
The modal style is within the css section:

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

You just have to change the dimension in CSS. The javascript doesn't do anything to the modal window except than center and display it.
Reply
Abhi 14 years ago
Hi Kevin, a nice example , can we restrict the user not to navigate on the parent window and make the exit possible only from the child, in other words can the child window not fade when we click outside it.
Reply
Kevin Liew Admin 14 years ago
Yes, remove this from the javascript section:

//if mask is clicked
$('#mask').click(function () {
$(this).hide();
$('.window').hide();
});
Reply
Olivier 14 years ago
Hi, if I include an iFrame into the modal window, what link/code should I put in the iFrame to close the window?
Thanks
Reply
Kevin Liew Admin 14 years ago
The iframe page and parent must be in the same domain:

first, you need a function in parent:
function closeModal() {
$('#mask, .window').hide();
}

inside the iframe, you can call it via:
parent.document.closeModal();

I have not tried that, hope it works.
Reply
Michael 14 years ago
The fadeIn() method looks self explanatory, but what are the parameters to the fadeTo() method?
Reply
Kevin Liew Admin 14 years ago
deborah 14 years ago
Hi ! Thank you very much for this lovely script and example. I have a question - how can I modify the script to re-size #mask and re-position #dialog on re-size of the browser window? Right now, if the user expands the window, the #mask falls short of the new size, and the #dialog also doesn't flow with the new page size. Any help is appreciated!

P.S. I found that by adding the following to the script under "Set the popup window to center", and then by loading up the script after the rest of the page, the dialog will size automatically to the content that is in it, which for me made it much more re-usable. :] Here is what I added:

$(id).css('height', jQuery(id).height());
$(id).css('width', jQuery(id).width());
Reply
Kevin Liew Admin 14 years ago
Add this:

$(window).resize(function () {

//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
$(id).css('top', winH/2-$(id).height()/2);
$(id).css('left', winW/2-$(id).width()/2);

});
Reply
Luke 14 years ago
There is still problem with this. If I put $(window).resize(function () as you said, then I don't have mask when activating dialog. When I resize the window then the mask shows up. There is also problem when you show the dialog window and then resize your browser, if the scrollbars show go right and you will see the mask is cut. Hope you can solve it. I like this simple modal window.
Reply
prakash 14 years ago
its not overlaying on youtube videos ...how do this?
Reply
Kevin Liew Admin 14 years ago
I guess you meant it appeared under the youtube video? You need to set WMMode to transparent in the youtube flash embed.
Reply
lharby 14 years ago
Hi there

I am trying to use this modalForm inside another piece of html which has been loaded using the jquery .load() method. It doesn't seem to allow the modalForm to work, I wondered if this should be the case.

My guess is that the code is not loaded correctly if it is nested inside some dynamically loaded html.

Any pointers greatly appreciated.


Luke
Reply
Kevin Liew Admin 14 years ago
You need to do this, change line 6 of JS code:

$('a[name=modal]').click(function(e)

to

$('a[name=modal]').live('click', function(e)

doing that it will parse the new DOM you have just added using jquery Load.
Reply
lharby 14 years ago
Thank you, that worked. Excellent.
Reply
Max 14 years ago
The modal window works perfectly but if I scroll down or up, the modal window doens't keep on a centered position. I see that you put the script for the resize case but I can't figure out where to put it. I mean, in a <script> apart from the original? or in the same code? Could you explain me please? Thanks a lot!
Reply
Kevin Liew Admin 14 years ago
The quickest way to fix it is, change the #box .window css's position from absolute to fixed.
postion:fixed;

You can put the resize feature (without the document ready bit), append it under the modal window javascript (inside the document ready).
Reply
Max 14 years ago
Thanks a lot Kevin Liew. That worked perfectly!!! I did what you told me and the modal window keeps its position and resize correctly. I really appreciate your help. I never thought you would answer that quick! That's what I call a real commitment. Thanks you!!!!!!
Reply
Kevin Liew Admin 14 years ago
you're welcome :)
Reply
Cenk Canbulat 14 years ago
Hi, Thank you for this tutorials. Is it possible restrict to opening. for example i added modal script to my index page. But when the visitor is surfing on the page and then return with home buton to homepage it is opening again. how can i stop this :D if you help me i ll be appreciated. Thx.
Reply
Ross Whelan 14 years ago
First off, awesome plug-in and thank you for the easy step by step instructions. You must spend a lot of time answering all our questions and I can only thank you for your dedication to top customer service.

My problem:

I am working within squarespace and have your plugin working within a jquery accordion plugin. I have a link on the accordion called 'Managment'. When the user clicks on this, the accordion slides open and reveals, in a list, the management team and their titles. What I want is for the user to click on a name and for your plugin to kick into action to reveal that persons bio.

The only problem is that when I click Management, and the accordion opens, the bios are already open, as if the persons name had already been clicked. Is there a way to have those bios hidden when I open the accordion rather than showing?

Thank you in advance for your help.
Reply
Kevin Liew Admin 14 years ago
ar, squarespace, used to be my sponsor :p

From your description, is it because of your CSS a:visited for the person bio? I can't really visualize it but if you can show me the test site and that would be good.

Anyway, two things I can think of based on your description:
1. You targeted the wrong Anchor tag
2. CSS a:visited
Reply
Anthony 14 years ago
Thanks for this very good tuto !!
I am using this simple modal window in my website (but with a custom look) and it works like a charm !!
@Jason : did you try to refresh your page (F5) ?? Because for me, it works with any size.
Reply
majid 14 years ago
the content of my scrollbar is dynamic (i.e. from the database). How do ensure that a vertical scrollbar shows up on modal when it is necessary? right now if the content is greater than the height then the content is going beyond the modal and on to the mask area. Thanks for any help
Reply
majid 14 years ago
actually, i think i got it. I added overflow:scroll to the #boxes #dialog css and it seems to be scrolling fine. Thanks for the great tutorial!
Reply