Simple jQuery Modal Window Tutorial

Written by Kevin Liew on 17 Mar 2009
674,909 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
Vanessa Colina 15 years ago
Answering @w00t question about cookies (how to make the popup show up only once), Include this plugin: http://plugins.jquery.com/project/Cookie and then rearrange the code like this:

$(document).ready(function(){

// if the requested cookie does not have the value I am looking for show the modal box
if($.cookie("modal") != 'true')
{

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

//if close button is clicked
$('.window .close').click(function (e) {
//Cancel the link behavior
e.preventDefault();
$.cookie("modal", "true", { path: '/', expires: 7 });
$('#mask').hide();
$('.window').hide();
});

//if mask is clicked
$('#mask').click(function () {
$(this).hide();
$('.window').hide();
$.cookie("modal", "true", { path: '/', expires: 7 });
});

function launchWindow(id) {

the same.. (this comment has character limit).
}
}

});

</script>
Reply
Mike Johnson 15 years ago
Hello, I've tried it but it doesn't work, I guess your code is ok, but I don't get it. Could you provide me the full code in a txt file please? with a link to it? (using rapidshare, hotfile, megaupload, or another free hosting service)?? Please?? I've tried alot to get it working, but I don't know how.
Reply
vodich 15 years ago
Vanessa could you please explain this part: $.cookie("modal", "true", { path: '/', expires: 7 });
What shoul be in the path:"/" ?
The code works fine with clicking the link but I need it to load only once onLoad and it doesen't work with the code you provided :( It's kinda urgent for me
Reply
Kevin Liew Admin 15 years ago
$(document).ready(function(){

// if the requested cookie does not have the value I am looking for show the modal box
if($.cookie("modal") != 'true')
{

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

//if close button is clicked
$('.window .close').click(function (e) {
//Cancel the link behavior
e.preventDefault();
$.cookie("modal", "true", { path: '/', expires: 7 });
$('#mask').hide();
$('.window').hide();
});

//if mask is clicked
$('#mask').click(function () {
$(this).hide();
$('.window').hide();
$.cookie("modal", "true", { path: '/', expires: 7 });
});

}
});

function launchWindow(id) {
... the same.. (this comment has character limit)....
}


How about that? I think the launchWindow function has to be taken out from document.ready. I haven't not tested. Just make sure you have the cookie mentioned by vanessa.

@vodich: grabbed from wiki: The cookie domain and path define the scope of the cookie, they tell the browser that cookies should only be sent back to the server for the given domain and path.

:)
Reply
DoÄŸan 15 years ago
Hi,
First of all great work, simple and effective.
But no matter how hard i try i could not figure out how to make it appear once with the help of cookies without any linking.
Would you provide me a js file which does that ?
Reply
dougie 15 years ago
I think I figures out a working version of this , which allows the popup to load once per session. Actually you can decide if you want it once or many times..its posted here on this forum..
http://www.dynamicdrive.com/forums/showthread.php?p=248683#post248683
Reply
ghanchi 15 years ago
this is well script thanks body but it is not working in IE 6 version(page Does not load ) ..Please reply me
Reply
dougie 15 years ago
Was looking for popup like this that will only load once per session. I finally figured it out and posted it here on this forum.. http://www.dynamicdrive.com/forums/showthread.php?p=248683#post248683
Reply
Madhu 15 years ago
Tkx frd....i used this for my site.
but i have little problem.i want to submit data from model window to my database without closing the model window.when i click the submit button in model window,the textfield data inserted into DB.but model window disappered.
pls help to solve this problem.it'z litle bit urgent.
Thanks again for this great tutorial.
Reply
Kevin Liew Admin 15 years ago
Pretty sure you can do it. Does your submit button trigger the onclick event that hide the modal window?
Reply
Charlie 15 years ago
Hi, thanks. Nice and simple tutorial. Really easy to implement.

I found a problem though. When the link to the popup is not at the top of the document but somewhere in the middle of a long document - you don't actually see the popup window on click. That is because the dialog is being positioned relative to the top of the document rather than to the top of the current view. I Tested this both in Chrome and Safari. Could you please help fixing that?
Reply
john 15 years ago
Hello,

I'm having the same issue with the pop-up always being at the top of the page did you manage to resolve the problem.

Thanks

John
Reply
Charlie 15 years ago
About my previous question. Just figured it out:

$(id).css('top', $(window).scrollTop() + winH/2-$(id).height()/2);
$(id).css('left', $(window).scrollLeft() + winW/2-$(id).width()/2);

Hope this is helpful. Thanks again!
Reply
Chad 15 years ago
Had the same problem - thanks for fixing....

Kevin you should add this to the script
Reply
mike 15 years ago
THX Charlie !
Reply
Menna 15 years ago
Charlie - this is exactly the solution I needed for my positioning problem - THANKS
Reply
Jerry 15 years ago
$(document).ready(function () {
//id is the ID for the DIV you want to display it as modal window
launchWindow(id);
});

------

I dont see the launchWindow(id); function code in the script that gets launched when this code is called. please advise. thanks.

Reply
Kevin Liew Admin 15 years ago
You can do it by creating a function called launchWindow(id) and chuck in all the code from javascript section. (exclude $(document).ready wrapper)
Reply
jerry 15 years ago
Kevin, I found this page which shows a sample of what you're referring to. Thanks for the help. Jerry

http://www.dynamicdrive.com/forums/showthread.php?t=56899 - page load code using queness modal
Reply
Amit 15 years ago
I have a for loop which displays items from database. I need to launch the modal window and also pass the id of the item via which the link was clicked and update some info to that item from the modal window input.

i need to get the item id inside the modal window.. Please help.
Reply
Kevin Liew Admin 15 years ago
I'm not sure what are you trying to achieve but you will need to add some code that grab your item item when this even is triggered : $('a[name=modal]').click(function(e) { ...... });
Reply
Stevs.net 15 years ago
Great code. Is there a way to fade the modal out as well as in?
Reply
Kevin Liew Admin 15 years ago
Change the hide() to fadeOut(), that will do the job.
Reply
Stevs.net 15 years ago
Worked like a treat Kevin, many thanks!
Reply
Renata 15 years ago
Hello,

I'm trying to put this PopUp to be managed from one dashboard.
Have already created the panel, connected with MySQL and is working properly, my problem is I do not know how to get the PopUp only open when the the item ACTIVE = 1.

I let down the structure of the database.
[CODE]
CREATE TABLE IF NOT EXISTS `popup` (
`id` int(10) unsigned NOT NULL auto_increment,
`titulo` varchar(150) default NULL,
`foto` varchar(150) default NULL,
`texto` text,
`active` tinyint(1) NOT NULL default '1',
`id_session` varchar(8) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;


INSERT INTO `popup` (`id`, `titulo`, `foto`, `texto`, `active`, `id_session`) VALUES
(1, 'Important', '798391b8f9c6.jpg', 'text here...', '1', '1');
[/CODE]

I tried to do this so that the PopUp only appears if ACTIVE = 1
[CODE]
<?php
$sql = mysql_query("SELECT * FROM popup");
$linha = mysql_fetch_array($sql);


$popupindex = '<div id="boxes">
<div style="top: 199.5px; left: 551.5px; display: none;" id="dialog" class="window">

<a href="#" class="close"><font color="#FF0000">Clique aqui para <b>FECHAR</b> esta janela e continuar navegando em nosso site!</font></a><font color="#FF0000">
</font></b>
<? echo nl2br($texto); ?>
</div>
<!-- Mask to cover the whole screen -->
<div style="width: 1478px; height: 602px; display: none; opacity: 0.8;" id="mask"></div>
</div>
';

$active = "1";
if($active == "1")
{
echo("$popupindex");
}
else
{
echo("");
}
?>
[/CODE]

Please help me, because with the above code to PopUp is always shown, even as ACTIVE = 2 which is the value that I put to be inactive.
Reply
Kevin Liew Admin 15 years ago
It's always popup because you have this:

$active = 1

$active will always equal to 1, therefore it always print out the popup script.
Reply
ton 15 years ago
Hello Everyone, i have use this script from this site http://www.dynamicdrive.com/forums/showthread.php?t=56899 - page load code using queness modal.
It works but I want to launch the modal window in a given time (x) but i have no luck using settimeout function.. pls help me
Reply
milan 15 years ago
Hi,
Thanks for great code.

What is the best way to adapt code so modal can return OK and CANCEL values?

Thanks
Milan
Reply
Kevin Liew Admin 15 years ago
Cancel should hide the modal. Ok should proceed to the corresponding action or link to the next page. You will need to create two buttons, and create on click event to both of them.
Reply
Peter 15 years ago
Very nice tutorial.
Can I in login dialog box verified data? I mean if password or username is wrong I want to see a message in login dialog box without opening it again. Now, I click submit and box is closed and when I open it again I saw that message. Please help, thanks
Reply
Kevin Liew Admin 15 years ago
Hi Peter, you can do it, but require fair a bit of modification. For example, you need to disable the default behaviour of submit button, verify the data using ajax, and display the result...
Reply
Tara 15 years ago
How exactly do you disable the default behaviour of the submit button? I too would like to have the login box verified. Thanks in advance!
Reply
Kevin Liew Admin 15 years ago
you need to give the submit button an id or class, then target it using javascript like this:

$('.button').click(function () {
return false; //this line disable the default behavior of the submit button
});
Reply
Kraki 15 years ago
You can also use jQuery UI and dialog widget.
http://jqueryui.com/demos/dialog/
Reply
Kevin Liew Admin 15 years ago
:) yep, but you will have to follow the default style and color scheme. A bit tricky to reskin it.
Reply