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.
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.
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);
});
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);
}
});
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();

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.<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
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
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
http://stackoverflow.com/questions/4780430/ie-problem-with-fading-in-text
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
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
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!!
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.)
- 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.
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
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.