Simple jQuery Modal Window Tutorial

Written by Kevin Liew on 17 Mar 2009
672,575 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
Steele 14 years ago
The code is pretty much working as expected except that I can't get the mask to appear with the dialog box...anyone have an idea why? I want the mask to show up so that if it is clicked, the dialog disappears...as it is, no mask, and if I click outside the dialog nothing happens.
Reply
Jeffronicus 14 years ago
I had the same problem until I looked at Kevin's sample pages and saw that the mask had the properties of left: 0 and top: 0; I added those and it showed up fine.
Reply
Michael 14 years ago
Great tutorial, great script, you're awesome for posting this along with the fantastic documentation. Simple to install and easy to understand, thanks so much!
Reply
brian h 14 years ago
how do i set the window to bottom of the page and does it support transparent flash video?
Reply
Kevin Liew Admin 14 years ago
I guess it can support transparent flash as long as you make the background of the modal transparent.
Reply
Akila 14 years ago
Hi
I am new to this jquery.
Can you please guide me how to install jquery and proceed with the modal pop ups.
i would be more glad to you if it was replied soon.
Reply
Kevin Liew Admin 14 years ago
Just download the demo, you should see how I link things up.
Reply
curdaneta 14 years ago
Hello,
I'm not able to close the modal window with the cookie sample on my local test. Could you please help me
Thanks
Ciro
Reply
Kevin Liew Admin 14 years ago
Cookie is working, but the close button isn't. I don't see there is any issue with your code, but try this button instead.

<button class="close">Cerrar</button>
Reply
curdaneta 14 years ago
Sorry, I forgot to add the sample link
http://www.iws.com.ve/misc/foo.html

Regards
Ciro
Reply
Pushpesh 14 years ago
Hello,

Thanks a lot for your awesome script. It works beautifully. However, i am including the overlay script in an iframe and i want the mask to cover the whole of the parent window's body. Is this possible.

Best Regards,
Pushpesh
Reply
John 14 years ago
First of all, I would like to comment that I have looked at a lot of modal window code, and this is one of the best. For the page I'm currently working on, I embedded the popup launch page in another page. As you might imagine (and for reasons this newbie can only partially comprehend), the modal window only appears within the boundaries of the embedded page, not on top of the page (index.html) that contains the embedded page.

It seems to me the only way to make it appear on top would be to relocate the modal window script to the containing page, but that's not possible since it is so closely tied to the embedded page content. Because of this I've unfortunately had to change my approach and am currently working with a more traditional popup window. If you have any thoughts on how this could work I'd love to hear them!
Reply
Kevin Liew Admin 14 years ago
I assume you embedded the popup in an iFrame. If that the case, I can't really help you. It has to be on index.html.
Reply
Jens 14 years ago
I havn't tried, but maybe this here could help:
http://forum.jquery.com/topic/trigger-from-iframe-to-parent-window
Reply
Ankit 14 years ago
Hi John,

I am facing the same issue as yours. How you resolved this issue ?

Reply
Sunny 14 years ago
First of all Great Tutorial. Thanks for sharing. Question tho' if I want to bring in the content within that modal from an external file like <a href="new-dialog.html".... how do I do it please?
Reply
Kevin Liew Admin 14 years ago
Hi sunny, unfortunately, not in this example. You can use fancybox.
Reply
Zia 14 years ago
I am unable to hide the #dialog Div. When I open the page it shows close button. but i want to show only Popup button and when I click on the the button then it should popup modal.

Your quick reply will be appreciated

Thanks
Reply
Kevin Liew Admin 14 years ago
Kayla 14 years ago
Great modal! And super easy to install and use.

I have one question though, is there a way to stop the background from scrolling until you have clicked out of the window? I noticed that there is a locker and unlocker in the .js file but I'm not sure that it is working.. how do I set things up to work properly in respect to this.. ?

Thank you!

Kayla
Reply
chemedeveloper 14 years ago
This is super awesome, thanks so much! I just have a question for you. My modal works awesome, except for cell phones. I notice that whenever I bring it up on a phone, it doesn't work correctly. It only shows up halfway, and the mask doesn't cover the screen. Any ideas on how to fix this? Thanks again for sharing this.
Reply
Frank 14 years ago
Hi there,

This is absolutely great! I implemented it on the "index" file of my site to give the user an option of languages they can view my website in, and it works flawlessly. The only thing is that when people are going through my website and they click home, since it was implemented on the "index" the popup comes out again. Is there any way to make the popup only occur once? So if they click back or index, they won't have to deal with the popup again? I know it can be done, but I'm not sure how to go about doing that. Can you help?

Thank you,

Frank
Reply
Kevin Liew Admin 14 years ago
Please read this section of this tutorial - Use Cookie on First Load
Reply