Simple jQuery Modal Window Tutorial

Written by Kevin Liew on 17 Mar 2009
674,833 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
Oliver 14 years ago
I have two a tags with the name set to "modal" the problem is only the first one activates the modal window. How can I set it up with multiple a tags that open different modal windows? Thanks
Reply
karl 14 years ago
I wanted to do the same thing!

You need to create a second #dialog like this:

<ul>
<li><a href="#dialog" name="modal">Simple Window Modal1</a></li>
<li><a href="#dialog2" name="modal">Simple Window Modal2</a></li>
</ul>

<div id="dialog" class="window">
Simple Modal Window1
<a href="#" class="close">Close</a>
</div>

<div id="dialog2" class="window">
Simple Modal Window2
<a href="#"class="close">Close</a>
</div>

and then obviously style #dialog2 with CSS.

Reply
Eray Tonyali 14 years ago
Hey Kevin, I have couple questions for you.
Please email me.
Thank you.
Reply
imran alvi 14 years ago
i want to call this modal window from the javascript function, how could i do this?
Reply
imran alvi 14 years ago
i copied the all jquery code in the page under javascript tag, then i used the launchwindow('#dialog'); at the onclick event in the javascript function of the gird cell. but it not working. it is working through the href tag <a href="#dialog" name="modal">Simple Window Modal</a>, please tell how could i call this window from my javascript function.
Reply
Kevin Liew Admin 14 years ago
You can read the " Launch modal window with Javascript" section.
Reply
Andrew 14 years ago
I like how you keep updating this making it better. But I have one question. When you minimize the window until there's a horizontal scroll bar. When you scroll, the opaque background doesn't move along with the scroll bar and you'll see a big white space
Reply
Kevin Liew Admin 14 years ago
I think you need the window resize function.
Reply
Andrew 14 years ago
I was able to implement the window resize function, and the modal window recalculates to the resize, its just the mask that doesn't appear to be resized. You can also see it on the demo. If you minimize the browser until you make the horizontal scroll bar appear, and you scroll to the right, the mask window doesn't move accordingly and only the modal window.
Reply
Kevin Liew Admin 14 years ago
Inside the $(window).resize, change this:
var maskWidth = $(window).width();
to
var maskWidth = $(document).width();
Reply
Andrew 14 years ago
Very Nice! Thanks :)
Reply
Adam 14 years ago
I found that you can switch the #mask in css to position:fixed, works the same... let me know if it works for you
Reply
Mich 14 years ago
I am using this piece of code to open a div tag after it check for value is checked, but i not opening the window.

My javascript to open the launchwindow, after validate checkbox.

but it open on page load.
I am using the javascript in the head,

$(document).ready(function() {

//Put in the DIV id you want to display
launchWindow('#suggestyourfavorite');

//if close button is clicked
$('.window #close').click(function () {
$('#mask').hide();
$('.window').hide();
});

//if mask is clicked
$('#mask').click(function () {
$(this).hide();
$('.window').hide();
});




this is my javascript action on body


<script type="text/javascript">// <![CDATA[
function suggestDealSubmit(){
if(document.getElementById("iAgreeCb").checked){
//Zenbox2.show();
launchWindow('#cityListDetail');
} else {
alert("You must read and agree to the rules first.");
}
return false;
}

// ]]></script>

Reply
Kevin Liew Admin 14 years ago
Did you include the main script in? Section 3 in this tutorial, the whole javascript need to be included.
Reply
Sahil 14 years ago
Kev, thanks a ton for this mate. I have tweaked this in a lot of ways towards the aesthetics of my website. You guys can try the Sign In and New Customer links. I have also tried too put in a loader image once the form is submitted. Since I know very little about Ajax, I have had to stick to basic form submission only.

For a lot of users with problems relative to centering, positioning, mask, fade in, fade out, scroll bars, multiple modal boxes on the same page, form submission, I have tried to tweak it as much as I could have in 2 days.

Live demo: www [dot] classyskin [dot] com

Kevin, I will be mailing you over the next few as I may need your help with Ajax!
Reply
Kevin Liew Admin 14 years ago
Nice! did you put overflow hidden when the popup is displayed.
Reply
Sahil 14 years ago
Yes, I did just that. The only problem is that the masked content of the website moves a few pixels to the right side when the modal is opened. I guess it is centering the modal again without the scroll bars this time.
Reply
Sriram 14 years ago
Sahil, I'm unable to see on your site where you've implemented Kevin's modal. Currently the login and registration links redirect to their respective pages.
Reply
Sahil 14 years ago
@sriram - The site is having some changes being made, this is why the modals are not working. I think you can check back by the end of next week.
Reply
Sahil 14 years ago
@Sriram - The sites back online. You can see it working there... :)
Reply
Oliver Rice 14 years ago
Really like the modal but I have noticed one problem when it comes to laptops the modal window and large modal content. Basically I have a large modal and the top half is lost under the top part of the browser and the rest of the modal is under the bottom of the browser window. For me its a problem because it is hiding the form submit button. Does anyone know how to amend the code to add a scroll to the entire modal window.
Reply
Oliver Rice 14 years ago
To expand, the problem occurs when the modal is taller than the main content.

Is there any way to make the main content at least as tall as the modal window?

Thanks
Reply
Kevin Liew Admin 14 years ago
I can't visualize your problem, would you able to upload it online?
Reply
swapnil 14 years ago
hi,
am facing a problem with athe modal pop-up am working on MVC3 and am trying to add apartial view to the modal pop up i can see the view for some time but after that the pop up is rendered blank...can you help
Reply
Sriram 14 years ago
Hi,
Very cool, absolutely loved it.Works like a charm.
I just want to know if navigation is possible inside the modal? I'm using this modal for a registration form
on my site; on clicking 'Create user' a success message will be displayed saying that a new user has been
created. The problem is as follows: I click on the 'Register' link->modal pops up->I fill in the registration fields and hit 'create user'->modal collapses and original page is displayed->i click Register again->I see the success message.
I use ASP LoginView controls for doing the above. Any suggestions? I would very much appreciate it.
Reply
Kevin Liew Admin 14 years ago
After you hit user, does the page refresh? Are you using AJAX?
Reply
MOM 14 years ago
Trying to launch the window, but always get:
launchWindow is not defined

Can someonle post a complete example- obviously I am not including somethying.
Reply
Kevin Liew Admin 14 years ago
It seems to be launchWindow function is missing, check this example:
http://www.queness.com/resources/html/modal/jquery-modal-window2.html
Reply
Poncho 14 years ago
function launchWindow(id) {

//Get the screen height and width
var maskHeight = $(document).height();
var maskWidth = $(window).width();

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

//transition effect
$(id).fadeIn(2000);


}
Reply
Kevin Liew Admin 14 years ago
Bacha 14 years ago
i wishI COULD send a personilze msg to the launch function (to be shown)
Reply
Kevin Liew Admin 14 years ago
Well, you can have whatever thing you want and any layout design as well.
Reply
Bacha 14 years ago
how can i put a html table inside the modal window ¡?
Reply
Max 14 years ago
I'm trying to open a #boxes #dialog{ inside an iframe on the same page containing this code, but its not working, after trying a lot of different script, i decide the post the question here, if someone know the Answer, your help will be very appreciated. Thanks
Reply
Kevin Liew Admin 14 years ago
If you used it within an iframe, the mask and modal will appear inside the iframe. It won't cover the whole page.
Reply