Simple jQuery Modal Window Tutorial

Written by Kevin Liew on 17 Mar 2009
637,383 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
kevin Admin 15 years ago
Hi Erwin, that's a good point, you can do it by getting the scrollback offset, then recalculate the top position. However, it's a bit tricky because IE uses different functions to get the value. So, what you need to do is, replace the following code with line 24 (line number based on tutorial above)

var y=0;
if (self.pageYOffset) // all except Explorer
{
y = self.pageYOffset;
}
else if (document.documentElement && document.documentElement.scrollTop)
// Explorer 6 Strict
{
y = document.documentElement.scrollTop;
}
else if (document.body) // all other Explorers
{
y = document.body.clientHeight;
}

//Get the window height and width
var winH = y;


and it should work the way you want.
Reply
Erwin 15 years ago
Hi Kevin,

just the thing I was looking for! Thanx! Just one question... I am designing a website with a one-page layout. At the bottom there are buttons to launch a modal window. After pressing one of the buttons the window opens at the top of the page, so I have to scroll to see it. Is it possible to open the window otherwise?

Greetings,
Erwin
Reply
Erwin 15 years ago
Hi Kevin,

Thanx for replying! Changed the code, the window now opens in the exact middle of the page (instead of the top), but i still have to scroll to see the window.

I want to use multiple modal windows, and the buttons to open them are spread over the entire page. Is it possible to specify coordinates for each window?

Greetings
Erwin
Reply
kevin Admin 15 years ago
Hi Erwin, I think I missed something... please replace

var winH = y;

with

var winH = y + $(id).height();

Try to use it in different position, it'd work... :)
Reply
kevin Admin 15 years ago
@Erwin: hey, i know what's the problem... my bad, so, this is the working solution:
replace this

var winH = y + $(id).height();

with

var winH = y;


and then, replace this:

$(id).css('top', winH/2-$(id).height()/2);

with

$(id).css('top', winH + $(id).height());

you see, the height is being divided by 2, that's y it appears in the middle of the page. :) Cheers.
Reply
Erwin 15 years ago
Hi Kevin,

Again thanx for your reply! Changed it, but I think I'm still missing something because the modal window still opens in the middle of the page.

I have my design up and running on www.erwinnijhoff.nl. As you can see it's a one page layout I am designing for my Aikido club. It has got an auto scroll funcion. At the bottom the are two links, 'Aikikai organisaties' and 'Sponsors'. These are some of the buttons I want to assign modal windows to. If you click them you will see the modal window opening in the middle of the page. It would be great if the window opens in a way you could see it immidiately.

Hope you can help, because as you will have noticed I am not a Javascript expert... (at all)

Greetings,
Erwin
Reply
Charlie 15 years ago
Hi there Kevin! This is wonderful code. I'm having a bit of trouble trying to place images on top of the window after it opens. I currently have my code setup to run my jquery plugin when the modal window opens, but once it starts pulling the pictures from TwitPic, the modal window disappears. Do you have any ideas?
Reply
kevin Admin 15 years ago
Hi Charlie, Thanks, but I have not tried it with TwitPic, it could be a conflict :(
Reply
kevin Admin 15 years ago
hmm, haven't try that in iFrame, did a rough search online, not sure if this will work,
http://forums.asp.net/t/1365548.aspx

otherwise, you will have to remove it.
Reply
Brian 15 years ago
Hi Kevin, great stuff! However, if I call a page to an iframe, and that page has a javascript function, once the javascript is activated, the key press (in this case set to 27 (esc), does not close the modal. The other methods - click the surround & 'close' - work fine. Any ideas? Otherwise, I think it is brilliant!
Reply
Brian 15 years ago
.... further to the above, I have found that if you click within the iframe - even one with no javascript, just plain old html, the effect is the same - the key press to close the modal doesn't work
Do I need to change my options and not offer a key press in these cases?
Reply
Brian 15 years ago
Thanks, Kevin - no joy unfortunately, so the key press close will have to go. I guess it is asking toooo many things to talk to each other!

Small price to pay for a great jquery opportunity - thanks again
Reply
Sean 15 years ago
Thanks so much for this! I know you can load the window when the page loads as I grabbed the code you posted above for this. I was just wondering if there is a way to only load it the first time they come to that page and again if they refresh the page?
Reply