Simple jQuery Modal Window Tutorial

Written by Kevin Liew on 17 Mar 2009
674,903 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
chris 15 years ago
I am trying to get this popup to load on page load, but I can't seem to get it to work. I'm just a little unclear on where to put the code for the on-load function. Do I just add the extra javascript at the bottom of the orginal script? I'm attempting to load this in wordpress and am having trouble getting it to work, even in no-conflict mode. and insight?
Reply
Kevin Liew Admin 15 years ago
Hi Chris, this example should able to answer your question :)
http://www.queness.com/resources/html/modal/jquery-modal-window2.html
Reply
Maddie 15 years ago
Hello,

I am trying to get mine to work, but absolutely nothing. I want it to say "Read more" and when you click that, the modalbox will show up. Rather, all that's happening is you click it and the url just changes to include the #dialog. If you have any suggestions, please let me know.
Thank you.
Reply
Kevin Liew Admin 15 years ago
It sounded like you don't have jQuery integrated properly. Check out the demo.
Reply
Erick 15 years ago
I am trying to get this to work on an image hotspot, please help!
Reply
Kevin Orin 15 years ago
Site: http://bit.ly/oPZ4Ly

Comment: Brilliant, best solution for a smooth popup in Drupal. 1 problem though, when the STAY INFORMED link s clicked on the TOP RIGHT menu, the mask shows up fine in all browsers except FF for MAC. How do I get the mask to always start at the top left with hidden overflow so it doesn't make the page scrollbars appear?

Kevin O. Williams
PRI : Web. Mobile. Print. The Works.
732.618.5084 (m) + 802.909.1014 (f) + www.priworks.com
Reply
Miguel 15 years ago
I'd like to know how to give opacity to the simple modal window, so the background can be seen a little
Reply
Kevin Liew Admin 15 years ago
You need this CSS apply to #dialog:

http://www.queness.com/code-snippet/5997/css-transparency-setting-for-all-browsers

however, you need to know that IEs don't render transparent text well.
Reply
Raghu 15 years ago
This is simple and working.. thanks for the example........ :)
Reply
Sunny 15 years ago
1. Good Job.
2. How can I call a external HTML within my dialog modal?
3. Better yet. if I can send some parameters like width, height, external_file.html, and use them to call the modal from anywhere?
Reply
Elliot 15 years ago
Hey, i got it all working fine, however just one small part that confuses me.

If you refresh the page, click for the popup to occur, it works fine. However, when you click off it, and then reclick the button, the popup works, but doesnt do the full fade out to black, then back in again slightly. Just goes straight to dim.

Cheers
Reply
Sunny 15 years ago
Hello, First of all this is GOOD. now I need some help please. I want my dialog box content to be from another HTML file. How do I do it? like my entire Dialog/Modal box to bring in another HTML file instead of from a <div id="dialog" from the same file.

Thanks to you and all the folks here helping each other.
Reply
Kevin Liew Admin 15 years ago
hmm, that's ajax. I can roughly tell you how to do it. You can only have one popup window because you have to mod this script.

Add a new div with id #content, then, inside here :
$('a[name=modal]').click(function(e) {
......
}

you need to add a $.ajax() call to get your html file. and then append it to #content. Check out jQuery documentation, it's really good.
Reply
Sarah Hart 15 years ago
Arun Tyagi 15 years ago
It's fine but i m implementing it with MVC2 asp.net it's not working.
please suggest me why it's not working.
Reply
szabofe 15 years ago
Just a tip (validator):
anchor rel="modal" and $('a[rel=modal]').click(function(e) {...
sorry
Reply
vikrant kumar 15 years ago
Awesome Work!!!!....I wanted to know when i scroll the page the content goes on top i have to drag to see the content..what to do see the content always on center of page.
Reply
Kevin Liew Admin 15 years ago
Since IE6 isn't a big issue anymore, you can use position fixed instead of absolute for #box .window.
Reply
Johan 15 years ago
Hello Kevin, first of all thank you very much for such a good tutorial. I just wonder whether we can also pass variable from DIV to Modal window. I mean we link to <div id="dialog"> by <a href="#dialog" name="modal">Simple Modal Window</a>, but can we even pass a parameter to <div id="dialog"> by using <a href="#dialog"> in some way?
Reply
Kevin Liew Admin 15 years ago
Yes you can, you will need to put a new attibute to the anchor data. eg <a href="#dialog" data="test-data">, but it's out of the scope of this tutorial because you will need to specify the handle for the data in the modal window.

You need to write a script to grab the data attribute from the A tag and process it based on your needs.
Reply
Ranieri Machado 15 years ago
Congratulations for the tutorial.
I am having bad time trying to centralize the popup window.
The sample code does not do that.
I would like to ask for help in this issue.
Reply