Simple jQuery Modal Window Tutorial

Demonstration Download

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:absolute;
  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); 
});

Launch Modal Window with Javascript

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

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 () {

        //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
        $(id).css('top',  winH/2-$(id).height()/2);
        $(id).css('left', winW/2-$(id).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

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 Mar 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();


AdvertisementWorried about 646-364 exam & comptia network+ preparation? We offer up-to-dated 350-040 dumps practice questions and F50-531 dumps with 100% exam pass guarantee of 640-816.

Show Some Love, Spread This Post!

567 comments

Dan Wed, 8th February 2012 This works great apart from forms. If I put form elements within the modal form and inspect them with firebug, it changes them to

<form name='myform'></form>
<input type='text' name='textbox'>

For some reason the form elements get placed outside of the form. Same form works fine outside of the modal box and inspects fine with firebug
Reply
Kevin Liew Wed, 8th February 2012 Weird. Have you try to submit the form?
Todd Fooshee Wed, 8th February 2012 Alright first of all, thanks for the script. It's great and really customizable, which I appreciate.

I did have one thing I was trying to do with it though that I can't seem to figure out.

On a particular page on this site I'm designing, I have some links that are at various locations down the page. You have to scroll for a majority of them. The problem is, as you scroll and click one of the links, the box comes up way back up at the top of the page. So what I'm wondering is, is there a way to change that so that the box always pops up in the middle of the screen no matter where you're scrolled on the page?

Thanks!
Reply
Kevin Liew Wed, 8th February 2012 Try to change .window position:absolute to position:fixed
Munir Tue, 7th February 2012 Thanks for this man, It helped me to finish my work :)
Reply
JesseD Tue, 7th February 2012 This tutorial doesn't seem to work in Safari.
Reply
JesseD Wed, 8th February 2012 Sorry I got to rephrase that, the Demo doesn't work in the new Safari for windows due to the Jquery library source isn't downloading. Great tutorial!
Kevin Liew Wed, 8th February 2012 hmm, I tested it with safari on mac and window, it works fine.
Brian Merrill Mon, 6th February 2012 Hello, The modal window is working perfectly but in IE8 I am getting a horizontal scroll bar when the modal window is launched. Is there a way to fix? Thank you, B
Reply
Kevin Liew Tue, 7th February 2012 hmm, that's weird, I have tested it on IE8 before. Was it the mask causing the horizontal scrollbar?
Benji Fri, 3rd February 2012 Hello,

how I can use one Script for 2 Popups?

I want create a Login popup and a Registration Popup, but I modify the css for the registration popup the size from the Login popup change too :(
Reply
Kevin Liew Tue, 7th February 2012 You need to specify different ID for the HTML, maybe add a class to the registration so you only change the modal with class specified. Check my demo, I have 2 different modals running side by side:

http://www.queness.com/resources/html/modal/jquery-modal-window.html
David Thu, 2nd February 2012 I have an IFrame that has a video inside it (flash). I'm using This modal window to show a video when a user clicks on a link. Problem I'm running into is on close, the video audio keeps playing. Is there a way to get the div to reset itself or any other ideas on how to solve?
Reply
Kevin Liew Tue, 7th February 2012 hmm, is your video in a video player? You need to find a javascript video player that allow you to control the play/pause of the video. This script hide the modal window, not destroy it, so basically the video is still playing but you just can't see it.
Arpan Wed, 1st February 2012 hey if you click anywhere except the dialog, the dialog disappears. I don't want it that way. The dialog should close only upon being closed from a button on the dialog . . . any ideas ???
Reply
Kevin Liew Tue, 7th February 2012 Remove this:
//if mask is clicked
$('#mask').click(function () {
$(this).hide();
$('.window').hide();
});
Alan Shacklock Mon, 30th January 2012 Sorry, one question if I may. How can I get this to pop-up on page load if a cookie has not been set, and then set the cookie if the user clicks a "Don't display again" checkbox on the popup? Cheers.
Reply
Alan Shacklock Mon, 30th January 2012 I did try following the instructions later down the comments from Vanessa Colina but couldn't get it to work as I couldn't get to the cookie plugin. Would really appreciate any further tips. Many thanks, Alan.
Alan Shacklock Mon, 30th January 2012 That is just brilliant - thanks you so much! I was struggling with the AJAX Toolkit trying to get a transparent image on a modal form, and you have done just that.
Reply
Jorge Haro Sun, 29th January 2012 Thank you so much, se que me va a servir mucho, gracias!! Saludos desde México :D
Reply
Irfan Sat, 28th January 2012 Thanks for the simple modal popup, it was easy to add your code.

my question is:
i have a small iframe within a page and when i open the modal popup, it does not occupy the full width of the parent window, it just fits only the small portion of the iframe. where do i have to change to occupy full screen.
Reply
Kevin Liew Sun, 29th January 2012 Hi Ifran, that's not the best way to trigger it. The modal window and mask size is limited to the size of the iframe.
Hazz Death Fri, 27th January 2012 and can i include easing plug in with this?.. n can u teach me how to do that? please..
Reply
Hazz Death Fri, 27th January 2012 hei, thanks for sharing this.. this is the most useful and easiest plug in i ever use.. thanks.. u can check it in here..

http://hazzdeath.blogspot.com

btw, how to change the transition efect?
Reply
John Fri, 27th January 2012 Brilliant script. I m happy now. Is possible for draggable? Thanks
Reply
John Mon, 30th January 2012 Good morning! I have added onto the javascript for dragger. Code;- $('.window').draggable(); That's all! :-)
David Bradley Tue, 24th January 2012 Hi,

Great script!!
Just one quick question, should it work when you put a modal link in a map area, eg:

<img src="images/image1.jpg" border="0" usemap="#Map1" />
<map name="Map1" id="Map1">
<area shape="rect" coords="169,18,276,92" href="#newaccount" name="modal1" />
</map>

I have tried this and when you click on it nothing happens, I know that the popup works as I have it link to a 'normal' href. I have also tried removing the 'normal' link temporarily, just in case you can only have one link per modal per page, however, it still didn't work.

Any ideas.

Thanks
David
Reply
joe Fri, 20th January 2012 I applied your tutorial to one of my client's site. http://www.i-wantmore.com. If you click on register and then clicked on 'Read terms and condition', the text overflowed to the right. It means that user will have to scroll right and down. How do i let it overflow only on y-axis and not on x-axis?

Another issue is very obvious on another site. Some users, especially mobile user cannot scroll the pop-up. Does this mean that their device cannot run javascript?
Reply
Adam Price Fri, 20th January 2012 Thanks, Mate! Exactly what I was looking for.

For people trying to get the background to fade in to black each time, add $('#mask').css({'opacity':1}); in the transition effect like this:

//transition effect
$('#mask').css({'opacity':1});
$('#mask').fadeIn(1000);
$('#mask').fadeTo("slow",0.8);
Reply
majid Fri, 20th January 2012 actually, i think i got it. I added overflow:scroll to the #boxes #dialog css and it seems to be scrolling fine. Thanks for the great tutorial!
Reply
majid Fri, 20th January 2012 the content of my scrollbar is dynamic (i.e. from the database). How do ensure that a vertical scrollbar shows up on modal when it is necessary? right now if the content is greater than the height then the content is going beyond the modal and on to the mask area. Thanks for any help
Reply

Leave a comment

Have something to say? Drop a comment! No HTML tags are allowed in the comment textfield.

Advertisement