Simple jQuery Modal Window Tutorial

Written by Kevin Liew on 17 Mar 2009
674,917 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
priti 15 years ago
I used a Flash Video,in the modal pop up in Html for this and the flash doesnt seem to work in any IE ..

<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab"
width="576" height="432" id="00000000-0000-0000-0000-000000000000">
<param name="movie" value="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab"
<param name="allowFullScreen" value="true" /><param name="menu" value="false" /><param name="bgcolor" value="#000000"/>
<param name="scale" value="exactfit"/><param name="AllowScriptAccess" value="always"/>
<param name="flashvars" value="at=bcfe240669b74223848fe1519727865c"/>
<embed name="00000000-0000-0000-0000-000000000000" src="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab"
flashvars="at=bcfe240669b74223848fe1519727865c" width="576" height="432" pluginspage="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab"
allowFullScreen="true" menu="false" bgcolor="#000000" scale="exactfit" AllowScriptAccess="always"
type="application/x-shockwave-flash"/>

</object>

Any idea on this
Reply
Kevin Liew Admin 15 years ago
okay, some debugging need to be done. Does your flash work when it's not on the modal window?
Reply
Andrew 15 years ago
Kevin,

Thanks so much for the great tutorial and code. The modal windows have worked like a charm and I have used this script numerous times. I am currently developing a splash modal overlay that centers on top of a website on page load. It works great in Firefox, Chrome, Safari, and IE8. However, the modal does not center in IE6/7 and will not overlay the flash content on the webpage. I have added wmode="opaque" to the flash object but still no luck. Do you have any suggestions on a fix for this?

Thanks again,
Andrew
Reply
Kevin Liew Admin 15 years ago
Do you mean have a flash content underneath the modal? I think it's wmode="transparent".
Reply
Mike 15 years ago
Hi, great tutorial!
I'm having an issue though where the text in the popup window looks jagged in IE7. Looks great in all other browsers I have tested. Even in IE8 you notice how the text is jagged when the window is fading in, but smoothes out and looks good once the fadein is complete. Any idea how or if it is possible to fix this? Thanks
Reply
Kevin Liew Admin 15 years ago
Unfortunately, that's the thing with IE, they don't render fading well. IE has anti-aliasing issue.

http://stackoverflow.com/questions/4780430/ie-problem-with-fading-in-text
Reply
Patrick Admin 15 years ago
Great tutorial! I love it, this method is much cleaner than most of the others I have used. Plus, I have plenty of options to customize. Thanks!
Reply
john munro 15 years ago
Hello,

Thanks for the script, I've got it working on the following site

www.digitaldmeocracy.org.uk

I have different modal windows coming up depending on which button is pressed to launch it using PHP.

The only problem is that due to the amount of content on the webpage the buttons are at differnet sections of th epage and when the button to open the modal window is used it always loads the modal window content at the very top of the page but not where the button is to open it.

How could I resolve this issue so the modal window only opens on the page where the button is.

Thanks

John Munro
Reply
Kevin Liew Admin 15 years ago
This modal window retrieve the position of the window, not the button. So, you won't able to do it.
Reply
bozzo 15 years ago
hi Kevin Liew
It's working as well for asp.net web pages content? Pressuming that the content for modal win. it;s coming from an normal html page?
thx
Reply
Kevin Liew Admin 15 years ago
yea it should be. it's just html, css and javascript. Just setup a working version and plug in your asp.net script bit by bit if that helps.
Reply
jack 15 years ago
that's nice
Reply
Max 15 years ago
No, it's not working for me either.
Reply
Kevin Liew Admin 15 years ago
have you tried the demo? I'm pretty sure it's working.
Reply
Cameron 15 years ago
The Demo works. But for some reason the styling of it gets all messed up when I try to make it work. The mask stays well below the information box which is incredibly annoying.
Reply
Kevin Liew Admin 15 years ago
Interesting, I think it can be caused by your CSS overrided my CSS. Can you check with firebug if my CSS got replaced by yours?
Reply
Arshad Vayani 15 years ago
For those people who are getting trouble can follow these simple steps to fix issues

first add top: 0; and left: 0; css properties in body tag

body { top: 0; left: 0; }

Than in script tags find
$jq('#mask').css({'width':maskWidth,'height':maskHeight});

after that add following code in new line
$jq('#dialog').css({'display':'block'});

I hope this works for you guyz as well!!
Reply
Shelly 15 years ago
I have the same issues as mentioned a couple of times above with flash video. I'm using this code in WordPress to pop up an embedded video using HTML 5 video with a flash fallback. I've managed to work your code enough so that it's pretty much flawless - I can even make the modal window close and shut off the video at the same time (so it's still not playing even when it can't be seen.)

Like the one guy above, in IE6 and 7, the mask overlays the video, so when you click to play it, it goes away (because you're clicking the mask, which is over the play button.) That one took some time, but Once I found the bug, I squashed it. You need to use a conditional comment to serve up a style to anything IE7 and below, and set all your outer containing elements (just the top-level ones and the mask: in my case, videos were being served from the content and sidebar, which were both housed in an outer div) with "position: static;". Bam, fixed. The mask won't show, but it's a small price to pay. So IE6 and 7 are not the script's problem, it's an IE bug that can be fixed with CSS,

However, another person has the same issue I do in IE8 - and it's sad that he didn't respond to your question so you could try to help, so I will.

In IE8, the window opens up, and the video player is there. If you click play,it'll load up and play - but the video doesn't show. The audio will play, but the video remains blank. I've discovered that this *is* something in the script. If I leave out the modal window, the video and audio play seamlessly as they should - but once you pop the modal script in there, no video in IE8.

(I had more, but apparently there's a character limit to the comments. You really should make people aware of that beforehand.)
Reply
Kevin Liew Admin 15 years ago
Ok, a few things you can test:

- mask overlay the video: this could due to the z-index value, try to change it something lower than the popup window
- wmode in flash, add wmode = transparent for the flash object

this what i can think of at the moment, I use it with flash video before.. it's fine.
Reply
che 15 years ago
Any idea how to put two different swfs on the same page, originating from two different links, using the same mask? I tried doing so and renaming and dupluicating modal1 and modal2 and boxes1 and boxes2 but the swf wouldnt appear in the second link.
Reply
Andy 15 years ago
Hi,
Great tutorial. But i have one problem - the background color doesn't go black. I mean when i click on Simple Modal Window - the text just pop up in between the page saying "Testing of Modal Window" - Should there be a image in background div that make it different color ??

Thanks
Reply
Kevin Liew Admin 15 years ago
not sure what's happening.. have you tried the demo? If the demo working for you, then it must be some code missing when you integrate it to your website.
Reply
Noel G 15 years ago
Hey Kevin, great plugin and nice addition there Charlie.

I have a page that uses a modal link in two spots. the first link is physically on the page while the second link is on a page that is loaded into a div using jQuery. In Firefox, chrome and all the normal browsers both links bring up the background and the window with the content just fine. IE6 and 7 however, do not display the window and content from the link that was located on the page that was loaded into the div. This means that the first link would work fine, but the second link only displayed the background. When I moved the link from the remote page on to the main page it worked just fine. NOTE: I did need to include the .js file on the remote page.
Reply
Rali Madhu 15 years ago
Great articles for jQuery Modal Window
Reply