Simple jQuery Modal Window Tutorial

Written by Kevin Liew on 17 Mar 2009
637,333 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
web tasarım 11 years ago
specialists to provide you with custom designs.
Reply
Agnes 11 years ago
Hi,

I've tried to use YouTube API to stop the embedded video on window close and mask click, but couldn't get it working neither iframe nor object (I've not really done js before, I must admit). Does anyone have a working example with this modal window script?
Reply
Magali 11 years ago
Awesome tutorial!
I have one question though, if you browse to your demo of the modal using Safari mobile (on an iPad or iPhone), and then zoom in, the popup doesn't automatically center. It just crawls into a corner of the browser. I have seen other modal popup tutorials which worked fine in Safari mobile, centering the popup, but I have a website with about 9 modal popups based on yours. I don't want to replace all that code...
So, any suggestions on how I can make the popups center in Safari mobile?
Reply
Evelyn 11 years ago
Hi! Thanks for this awesome post.
It will really work on my website, if you are able to help me to solve this problem.
I have a content DIV, but it will not cover the whole content page. It will only cover the bottom of the link.
I even brought <div id="boxes"> above <div id="content">. It didnt work too.
I hope you are able to help with with this.
By the way, I am using twenty ten wordpress theme to cuztomize.
Your prompt reply would be greatly appreciate.
Thank you.
Reply
Evelyn 11 years ago
Hi there!
What if I have multiple links in one page? By the way, I am using Wordpress.
I created three links in one page. When I click on the 2nd link for the 2nd popup window, it appears to have the same description as the 1st popup.
What do I do now?
Please help! I am really desperate trying to finish this website for a friend by tomorrow.
Thanks
Reply
charles 11 years ago
helped me alot thanks :)
Reply
Charles Moore 11 years ago
On the script. When you click outside of the box or "Close it", it uses .hide() .. For a better effect chage .hide() to .fadeOut(300)@
Reply
Kirk 11 years ago
Instead of using jQuery to do window height/width, just use CSS. Add " height:100%; width:100%; " to the mask div, and then violla. As for positioning the modal window, use " position: absolute; top: 50%; left: 50%; margin-top: -101.px; margin-left: -187.5px; " and this will always keep you centered without having to keep jQuery running. Uses less processing power in the browser, and results in cleaner, shorter code.
Reply
Kirk 11 years ago
Also, I forgot to add that you can also stack jQuery commands on top of each other. For example:

$('#mask').fadeIn(1000);
$('#mask').fadeTo("slow",0.8);

can be shortened to:

$('#mask').fadeIn(1000).fadeTo('slow',.8);

Again, less code, less room for mistakes.
Reply
debianick 11 years ago
Thanks, it help me a lot.
Reply
rcp 11 years ago
Great job, great explanation,! simple&quick but effective! Thankyou
From Spain
Reply
kokopeli 11 years ago
hello. nice work indeed!
but have an issue...
When i place an asp:button (or whatever object wich causes postback) in it, on postback the modal disappears.
is there a way to keep the modal open after postback?
thanks
Reply
Kevin Liew Admin 11 years ago
You need to use AJAX post.
Reply
ELVER FLOREZ 11 years ago
HI, I TRY OPEN TWO MODAL WINDOWS FROM A ASP WINDOWS, BUT ONLY ONE MODAL RUN. YOU CAN HELP ME? PLEASE. MY EMAIL IS EFLOREZ09@GMAIL.COM
Reply
kundan 11 years ago
nice tutorial. thanks for sharing.
Reply
Adnan 11 years ago
This great function but how i add the delay in this script. Actually i want this pop up appear after 10 or 20 seconds. any body help me. Thanks in advance.
Reply
Kevin Liew Admin 11 years ago
Please refer to section 4. The only code you need it:

setTimeout("launchWindow(id)", 10000);
Reply