Tutorials

Simple jQuery Modal Window Tutorial

Written by Kevin Liew on 17 Mar 2009
455,634 Views • Shares
797 comments

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
Kongen 4 years ago
Seem that the modal window in delayed on IE, while on Firefox and Chrome it works as expected. I'm running IE 8, anyone else experienced a difference between IE and fx Firefox in how the window is displayed?
Reply
Ravindra 4 years ago
This is good one....but i don't know on which button or link it shoud be placed .....please me as soon as possible....... where to place it?
Reply
preet 4 years ago
Hello preet,
its nice for who want help this things by this page i collect many information
Reply
web tasarım 4 years ago
You people overreact the same way with every pre-sale. Just be patient, you'll get tickets with everyone else when they go on general sale. It's not like he's Jeff Mangum or this is his last show ever or anything teacher
Reply
Alan Maia 4 years ago
Create the Cookie only if clicked Close


$(document).ready(function() {

//if the cookie hasLaunch is not set, then show the modal window
if (!readCookie('hasLaunch')) {
//launch it
launchWindow('#dialog2');
}

//Put in the DIV id you want to display
//launchWindow('#dialog2');

//if close button is clicked
$('.window #close').click(function () {
$('#mask').hide();
$('.window').hide();
//then set the cookie, so next time the modal won't be displaying again.
createCookie('hasLaunch', 1, 365);
});
Reply
giovine 4 years ago
Thank you very much. I was looking for a solution to "modal" effect and your way is very smart.
Reply
John Pachi 4 years ago
I used your modal and it works perfectly, but here's a challenge I'm struggling with. I want to cycle through different modals with keys on the right and left side of the modal. Could you post something to this extent?
Reply
Punyada 4 years ago
This is absolutely nice .. i have on query i tried doing two modal pop ups on one page one with Dialog1 and other with Dialog2 id but the second Dialog2 doesn't function properly. Could you please provide some help.
Thank you.
Reply
RobB 4 years ago
So I tried using this to hold youtube video embeds. It works great, minus the one setback that once you click on the mask the video hides but the audio keeps playing. I'm a novice with jquery at best, and was wondering if there's a quickfix line of code that any of the more experienced in the audience might know of which will make the video shut off completely when I click on the mask. Thanks big time.
Reply
Kevin Liew Admin 4 years ago
okay, this one is a tricky one, you will need to use YouTube API:
http://stackoverflow.com/questions/6671232/youtube-api-stop-video

Then you need to put it inside $('.window .close').click and $('#mask').click
Reply
John Pachi 4 years ago
I'd like to be able to cycle through different modals, but I'm struggling with implementation. Could you outline something with a cycle left/right on the respective side of the modal window?
Reply
Kevin Liew Admin 4 years ago
hmmm, I dont have one. This feature is quite unique. How about fancybox with iframe?
Reply
John Pachi 4 years ago
I'll look into the fancybox with an iframe. On another note, What about scrolling? For instance, I've heavily modified the modal but if there is too much information in the modal it gets to big for the screen, and with this implementation, only the background scrolls and not the modal. I'd like to reverse that. I've tried different methods but everything seems to break.
Reply
Kevin Liew Admin 4 years ago
haha. To get that behavior, you can modify #boxes .window position fixed to absolute.
Reply
John Pachi 4 years ago
So I tried that and it somewhat works but it is very messy. The bigger issue though is that I can't get the mask to, if you will, scroll with the modal. The mask remains fixed to the screen size even though I have modified it not to, tried to modify the script, it broke. I was hoping there was a jquery fix for the scrolling, one where I wouldn't need to mess with any more CSS
Reply
Alex 4 years ago
Sort of a beginner question, but how do I change it so that the popup box has a fixed position from the top. I'm guessing I have to change something inside of this:

//Set the popup window to center
$(id).css('top', winH/2-$(id).height()/2);
$(id).css('left', winW/2-$(id).width()/2);

But instead of being dead center, I would like the pop up box to be centered only horizontally, and then fixed to about 150 px from the top of the page.
Reply
Amy Whitman 4 years ago
I am looking to do something like this combined with a tooltip type method to create a tutorial on my web page for the end user. Going through the steps highlighting and pointing out different parts of the page. Any suggestions??
Reply
MrKatsie 4 years ago
Hi! Great script, very easy to implement, however, I have one problem: I have modal window running viddler videos, which work fine, but when the user clicks the close button the video keeps playing. is there anyway to stop the video when closing the window?

any help would be greatly appreciated! here's a link: http://www.katsiedesign.com/KK/index.html#4
Reply
Kevin Liew Admin 4 years ago
Does viddler has some kind of javascript api that allow you to control the video player? If it doesn't, I guess the best way would be removed the popup entirely. Doing this, you won't able to show the modal again, the user will have to refresh it.
Reply
MrKatsie 4 years ago
Thanks for the reply - you're right, I've had to remove it and just have it open in a new window. still using this on the email form though - works a charm ;)
Reply
Scott 4 years ago
Hello, I have been reading great things about this, and I tried it myself because I need a popup form for a mailing list. Where everyone else is having success, I click the href for the a tag, and nothing happens. In the address bar, it still links to the div like it wants to open, but nothing shows. Am I missing some name we have to change when implementing?

I am also using asp documents instead of html, could that be the problem?
Reply
Kevin Liew Admin 4 years ago
Make sure jquery is linked properly. You can check for javascript error using the developer inspector. Check the console and check the resource loaded.
Reply
jonathan 4 years ago
Is it possible to open a html instead of an image?
Reply