Simple jQuery Modal Window Tutorial

Written by Kevin Liew on 17 Mar 2009
674,915 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
Biju Subhash 15 years ago
thanks..
here an another simple popup link for your readers :
http://www.bijusubhash.com/blog/simple-popup-using-css-and-jquery
Reply
Steven 15 years ago
Great code dude...
Btw, how can I trigger hide() without click, but by using setTimeout.
Reply
Kevin Liew Admin 15 years ago
create a function called autohide()

function autohide() {
$('#mask').hide();
$('.window').hide();
}

then use the setTimeout to call the autohide function. you need to put setimeout inside the modal window click event.
Reply
Ranjith 15 years ago
Instead of "<a href="#dialog" name="modal">Simple Modal Window</a>" How can I activate the same by using Linkbutton in asp.net?
Reply
Kevin Liew Admin 15 years ago
not sure, im a php guy, know nothing about asp.net.
Reply
Bryan Fisher 15 years ago
Works for me. Check it out in action: http://pastureprooffer.com/
Reply
Natalie 15 years ago
I need some help. I am so new to this and am very confused. What is jquery framework? The html file from the download or a different js file? When I test the window all that happens is a large black box appears at the bottom of my page. I have to scrolll down to see it. I have the modal window html from the download in my root folder.
Reply
Kevin Liew Admin 15 years ago
jQuery is a javascript framework that meant to help us to code javascript faster. for more details visit: http://www.jquery.com

I'm not sure what's happening to your demo version, it should display a popup window.
Reply
Natalie 15 years ago
I got the window to work! I do have one other problem. The Mask doesn't appear. Also I can manipulate other things on my page when the modal window is up. Is it because I have a swf file in the modal window?
Reply
Natalie 15 years ago
Also where do you type wmode=transparent in the flash file? It is my other flash files that fail to remain inoperable when the modal window is up.
Reply
Natalie 15 years ago
I changed my flash file to wmode=transparent. It didn't change anything.
Reply
Kevin Liew Admin 15 years ago
I assume you embed the flash using the basic method, this is where you should put your wmode:
http://www.ajaxapp.com/2011/05/10/flash-z-index-fix-by-setting-wmode-to-transparent/

but, I don't think you will need it, because the swf file is in the modal window, not underneath it. So, what's the issue you have with the flash file and modal window?
Reply
Natalie 15 years ago
Sorry I wasn't clear. Your tutorial worked up until I exhanged the simple text for a swf file. The mask no longer appears and my other swf files (thumbnail gallery and a menu) can still be manipulated when the modal window is open. And your right, the wmode options did nothing.
Reply
Kevin Liew Admin 15 years ago
Ok. Make sure <div id="mask"></div> is in your html file. I dont really know what's happening. If all failed, I would recommend you to use fancybox, my favourite modal window Fancybox supports swf file, so it should work in your case.

http://fancybox.net/
Reply
Natalie 15 years ago
I appreciate your suggestion but unfortunately I have no idea how to incorporate fancybox. I don't know how to write my own java script or incorporate it into what you have provided above.
Reply
Kevin Liew Admin 15 years ago
Would you able to describe how do you want it to work in your webpage? Is it a couple of links, when user click on it, it displays the swf file?
Reply
OÄŸuzhan BaÅŸar 15 years ago
How to auto open modal window? <body onload= ??? >
Reply
Kevin Liew Admin 15 years ago
<body onload = "launchWindow(id); "> . . . . . </body>
Reply
Ray D 15 years ago
I have your script running and I want it to auto load when the site opens up, Im using the sticky note and I see you have this.

$(document).ready(function () {
//id is the ID for the DIV you want to display it as modal window
launchWindow(id);
});


How do I use this code can some one modify the existing code for me and make it so I can upload the whole thing and have the sticky not appear as soon as you hit my website.

Thanks so much in advance.
Reply
Kevin Liew Admin 15 years ago
Mike 15 years ago
Hi

First of all, I want to thank you for this little piece of jquery which is simple to use and looks great. Thanks for sharing it with us ^^
I'm using it in the site I'm creating but I have a slight problem. Everything is working out great except for the fact that the window (and even the mask) is badly out of place. When I first tested this on a an example website it was all centered and the mask covered the whole screen, however, in my website it's not centered and the mask appears at the bottom of the page.

Also, it seems that for some reason, the Css that I applied to it isn't recognized by all the elements. Some of them are styled, others aren't... I don't know what's up with that.

Any ideas on this?

Best regards,
Mike
Reply
Kevin Liew Admin 15 years ago
I reckon, it has something to do with the CSS. The mask appeared below because it doesnt have position absolute set properly. You need to check your CSS, make sure they are linked. Other reason, it could be your existing CSS overwriting my CSS code.
Reply
Ahmed 15 years ago
I really like the idea behind Modal window and i know how its useful.

But all Modal Window and other similarity are triggered after CLICK event. I have to click on SPECIFIC ID to get Modal Window shows up.

What i'm looking for to have simple Modal Window build by jQuery and it get triggered when user select any text from web page (plain text from P or SPAN tag). And when Modal Window open up it has some data or links or some tabs inside that Modal Window each tab has its own data such as forms or links, images, audio, video, ....etc

I hope i'm clear and explained myself enough. Im still new to jQuery and searching a lot for such solution or close solution to my idea, but i cant.

I'll be so grateful of you can guide me or show how and where to start. Or is it really possible to that.

Thanks a lot
Ahmed
Reply
Steve-o 15 years ago
Hey Kevin!
thanks so much for the tut. I really appreciate it, and feel supported to know that people are out there offering things I can't do. I have implemented your modal window and it works great but for one thing. My browser will automatically scroll down so that the modal is touching the top of the screen. I haven't the foggiest idea of where to begin sorting it out.
Thank you!
Steve
Reply
Joe 15 years ago
Hi there, thanks for the plugin.

Is there a way for me to pass variables from the link I press to the popup window?

Because I can only put a hashtag into the link e.g. href="#dialog" I can't pass variables in the link like so: href="#dialog?var1=variable&var2=variable2"

I've got a series of links each opening up the same window but each needing to pass a unique variable, is there a way to do this? (i'm using PHP).

Thanks
Reply
Kevin Liew Admin 15 years ago
With PHP you can. I assume everytime you pass the variable, it refresh the whole page? So, I think in the HTML, you just write your variable to the modal window.
Reply
Sergey 15 years ago
Thanks, I've used it
Reply
Toufiq 15 years ago
Hi....
First appriciate you for your nice work.i used it in a web site.but there is a problem...when i clicked a large image a video ll start automatically by modal window...but the problem is that when i m using ie 7/8/9 video is continued when i clicked close button.but chrome & firefox did it perfectly.but i need the solution urgently for my client.if you help me it would be a great pleasure for me.here is url of my site http://www.andgateit.com/partner4/dvc/
please check & if possible give me a solution as early.

Thanx again.
Reply