Register now or login here to start promoting your blog and your favourite articles.
Simple jQuery Modal Window Tutorial
17 Mar 2009 - 153 Comments
In this tutorial, I'm going to share how to create a simple modal window with jQuery. It selects all the anchor tags with name attribute set to "modal" and grab the DIV #id defined in the href and displays it as a modal window. jQuery has made everything so simple, be sure to check out the demonstrations, examples I made. It looks good :)
Author: kevin | Source: queness
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.

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

Copyright & Usage

The effects and techniques demonstrated in tutorials on Queness can be used in whatever manner you wish without attribution. You cannot copy whole tutorials (unless permission is given), either in English or translated to another language.

Share This Post to Support Me! :)


Comments

Thor Larholm on 17 Mar 2009 says:
The two last click handler functions seem excessive, since they could be combined into one with an expanded selector.

$('#mask, .window .close').click(function () {
$('#mask, .window').hide();
}
kevin on 17 Mar 2009 says:
Hi Thor, thanks for your information. I have updated the code. Cheers.
Nooomad on 17 Mar 2009 says:
You can create so beautiful things using JQuery! It's amazing
Johnny on 19 Mar 2009 says:
Hi Thor, I've been looking for a free script for a modal window using mootools 1.2 but was having no luck. After reading your tutorial, I think I have an idea how to build my own. Thanks a lot!!!
kevin on 19 Mar 2009 says:
Hi Johnny, I'm glad you like this article. If you having any problems at all, don't hesitate to ask me : )
yvonnia on 22 Mar 2009 says:
Hi Thor, I'm new to Jquery/javascript. Can you tell me why the popup keeps appearing in the extreme bottom right of my screen and why the actual dialog info is appearing at the top center? (using Firefox)
yvonnia on 22 Mar 2009 says:
Nevermind. I figured out that I had to adjust the positioning (oops). Awesome tutorial. Thanks a bunch!
kevin on 22 Mar 2009 says:
Hi yvonnia, yea, good to see that you hv figured it out, and, any questions, please ask again.
Brandon on 23 Mar 2009 says:
If the page is fairly long when you click the link it jumps to the top, is there a way to prevent this?
kevin on 24 Mar 2009 says:
Hi Brandon, thanks for your comment. I solved your problem. Please refer to the Update section in the article and check the demo too. Cheers. :)
Nicolas on 24 Mar 2009 says:
Hi. Thanks for it. I'd like to use it but without a link. I will make it work by using a test.
How can I do it ?
kevin on 24 Mar 2009 says:
@Nicholas: Are you looking for a download link? It's all in the article, download and demostration.
Nicolas on 25 Mar 2009 says:
@kevin : No. Actually, I'd like to use this code, but not by a clic.
The "pop up" launches when you clic on a link.

Or I'd like to launch it when the empty test of my fields is true.

I guess, the only thing to change is the beginning but I'm a noob in Ajax, and my english is maybe not good enough to explain what I'd like to do.
Markvoce on 25 Mar 2009 says:
Just a quick query, when I click the link the popup box is appearing in the center however on a long page, the page is scrolled to the bottom. Any guesses. I have tried winH = $(document).height(); as mentioned in the updates.
kevin on 25 Mar 2009 says:
@Markvoce, you can try to put
winH = $(window).height();
$(id).css('top', winH/2-$(id).height());
kevin on 25 Mar 2009 says:
@Nicholas: Ok, getting there. But I don't understand what you meant by "empty test of my field". Do you mind to elaborate more about it? I'm ready to help. : )
Markvoce on 26 Mar 2009 says:
@kevin, I have tried what you suggested, the modal box now appears at the top of the window and the page scrolls down half way.

If I exclude the $(id).css('top', winH/2-$(id).height()); line the modal box appears at the top of the page with no scrolling.
kevin on 26 Mar 2009 says:
I think you have to calculate the position by getting your modal window's height. Do you mind to show me your example?
Markvoce on 26 Mar 2009 says:
@kevin, yeah sure you can view it at
http://timepg.com/test/test.htm
The link below the first paragraph.
kevin on 26 Mar 2009 says:
Right, I saw it, you want it to display in the middle of the screen? and hey, I think you may want to put the e.preventDefault() under this as well:

$('a[name=modal]').click(function(e) {
......
});
Markvoce on 26 Mar 2009 says:
Yes the idea would be for the modal window to appear in the middle, no matter where the page is scrolled to. Cheers
kevin on 26 Mar 2009 says:
@Markvoce: Hey, I think I solved your problem, please check the updated code : )
Nicolas on 30 Mar 2009 says:
@kevin.
It's nice to help me.
Actually I have a JS function :

function verifAll(form)
{
var formulaire_ok = true;
var imgs = form.getElementsByClassName("verif");
for(var i=0; i
kevin on 30 Mar 2009 says:
@Nicolas: I think I know what you mean. Instead of launching it using Link, you want to launch by using javascript calling the modal window.

In order to do that, 2 things you have to do:
- move the modal window code to a new function
- remove the anchor tag detection code

So, I have created the example for you, view source to see the code. Hope this will finally meet your needs. : ) Cheers!

Launch Modal Window with Javascript
MarkJ on 31 Mar 2009 says:
Ah, this is just what I was looking for, except I can't get it to work in IE6? The mask covers the modal window when I try to use it, so does the example you provided?
Nicolas on 31 Mar 2009 says:
Thank you very much.
I had to modify it but now it works very well.
Nicolas on 31 Mar 2009 says:
It's me again.
Sorry to disturb.

I have a question and a problem.

My problem is that it doesn't work with IE but your example works with IE. I don't understand why.

And my question is : My dialog box is just used with an ok to close it. It doesn't work with my keyboard. I would like to put enter to close. Do you know if it is possible ?

Thanks a lot.
kevin on 31 Mar 2009 says:
@Mark J: Hi mark, It was a small mistake, now it's working now. I have changed:
#boxes .window {
position:absolute;
......
}

The PNG background is not displaying correctly tho, you will need pngFix for it. (hate ie6)

@Nicolas: Not sure what is happening to your version. You might have to check carefully. Again, try the position:absolute as well.

For your question, add this, and it will work : )

$(document).keyup(function(e) {
if(e.keyCode == 13) {
$('#mask').hide();
$('.window').hide();
}
});
Raido on 1 Apr 2009 says:
Hi! I wanted to say thanks for that example You made for Nicolas. It seems to fit for me quite well too. (I'm trying to open modal window when "Add new" is chosen from
list. :) )
Raido on 1 Apr 2009 says:
By the way...when I have long page(scrollbar is visible) and when I'm at the end of the page, modal still appears at the beginning of the page. So I have to scroll up. Might it be my mistake or does this script just works that way ? :)
kevin on 1 Apr 2009 says:
That's the behaviour of the script, you can try to put position:fixed in the .window class. But it will cause some problem in ie6. Yea, just try that...
Raido on 1 Apr 2009 says:
I'm still waiting for that day when IE6 will be ashes. :)
If You know CSS well, it's possible to find fixes for IE, but if You know basic CSS like me, then IE6 is real pain in the arse. :)
But yes, that position attribute fixed it ...and I'm going to ignore IE6 at this time. Actually it's quite good idea to make some complications to IE6 users...and there should be a small note: "If You encounter any bugs on the site, know, that they are because of the browser You are using. " It's called browser racism. :)
Once again, thank You Kevin.
kevin on 1 Apr 2009 says:
@Raido: you're welcome. haha, out there, they have petition to ban ie6! : ) ie6 has been causing heaps of problems.

Btw, hey, you actually can try this, after the window class add this line:

*html #boxes .window {
position:absolute;
}

only ie6 will able to interpret that line. So, all the browsers will use position:fixed except ie6. Of course, you will have the scrolling problem in ie6, but hey it will be far more better than couldn't display it at all! :)
Raido on 2 Apr 2009 says:
Thanks, I might try that. Today it's unfortunately impossible.
And talking about IE6, today I was sent a link: http://www.saveie6.com/

Kinda ironic. :)
kevin on 2 Apr 2009 says:
haha.. that's hilarious. look at this one:
http://www.stopie6.com/

I read an article from arctechnica (forgot the link)... the usage of ie6 is dropping prominently, in Europe tho... so, yea, it's just a matter of time...
Nicolas on 5 Apr 2009 says:
Hi Kevin, it's Nicolas again.
Actually, I tried but I don't understand why it doesn't launch on IE.
I upload the test, could you look and tell me what's wrong please ?

Link : http://devilangels.free.fr

Thanks for all.
kevin on 5 Apr 2009 says:
@Nicolas: hi, I looked at your code... and it's killing me :P... I think the modal window is working, because I can launch it using:

<input type="button" onclick="launchWindow('#dialog')"/>

however, the position:fixed causing it display behind the mask, you might want to put it back as absolute in IE6.

So, there is nothing wrong with the modal window. I think is your validation script causing the problem. In ie6, when you click the "Envoyer le message" button, if you observe carefully, ie6 submit the form.
Nicolas on 11 Apr 2009 says:
Hi Kevin !

Everything is ok now. It works very well.
To close de window with enter (keyboard), your function didn't work.

However if you put :
$('.window .close').focus();

it works very well.

Thanks for everything.
Franco on 15 Apr 2009 says:
Hi, very nice script, easy to use for those who don`t understand Java(like me).
I want to put the styles on my .css style sheet but if I do that it doesn`t work correctly, can U healp me? (Sorry about my english)
kevin on 15 Apr 2009 says:
@Franco: I think you just have to put the CSS code inside your file. Make sure the #mask and #boxes are not duplicated. It should work :)
Manzar Alam Baig on 17 Apr 2009 says:
No comments
Robert Reynolds on 23 Apr 2009 says:
Great tutorial. I am trying to create a popup modal box and have it load dynamic data that is already on the page. Magento ecommerce category page with a list of products. An example can be seen here, http://www.ae.com/web/browse/category.jsp?catId=cat10025 , by mouseover a product image to reveal "Quick View" and click to see modal window. Any suggestions how I would go about this? Thanks in advance.
kevin on 23 Apr 2009 says:
@robert: yes, it's totally doable with jquery... not sure bout the implementation, but after i look at it, it uses iframe in the modal window. Of course, server side language as well, ignore that sentense if u gonna hardcode it.

so, i guess this is how u do it, just the concept tho:

1: mouseover event for each items listed, so that a quick view button will display, otherwise hidden.

2: click on the quickview button, it actually passes the url with item id and display it in the modal window with iframe support.

3: you will need to construct a page that accept the product id, and display all the details accordingly.

yea, i think that's about it.. :)
Neil0 on 28 Apr 2009 says:
Awesome...just one question. How do i get the modal window to close on the submission of a form.
Ortubes on 28 Apr 2009 says:
How do I make the modal window automatically when the page loads?

example: http://digaki.com/confirm.jpg
kevin on 28 Apr 2009 says:
@Neil0: not sure, maybe u can do it like this: $('.window .close').click();

I havenot tested the code.

@Ortubes: Yes, someone has asked this question before. and here is the solution
http://www.queness.com/resources/html/modal/jquery-modal-window2.html
Ortubes on 29 Apr 2009 says:
Thanks, I do it the way wanted. test to see if it was good.

http://digaki.com/tecnologia/teste-jquery
teodore on 30 Apr 2009 says:
on IE 6.0 dont work
kevin on 30 Apr 2009 says:
@teodore: It works in ie6. Do you mean the png rendering?
D on 5 May 2009 says:
This seems to work for me except the masking DIV appears at the very bottom of the page, after the main page content. The Dialog div appears where it should. Ideas?
JG on 7 May 2009 says:
Amazing tutorial, really helped me.
Anil Konsal on 20 May 2009 says:
Very nice tutorial. i have been using jquery ui dialog but still need my own for customizations.

Thanks a lot!
Krzysztof on 21 May 2009 says:
And how can I display #dialog1 when page loads?
daves on 21 May 2009 says:
This works great but if I try and save the download it no longer works in IE. Why is that?
kevin on 21 May 2009 says:
@Krzysztof: Hi, I have added a new section in the article "Launch modal window with javasccript" and included an example as well. Cheers :)

@daves: oops, I updated the article, but had forgotten to update the zip file! I have fixed that, it's the position problem. :)
april on 28 May 2009 says:
hey there kevin! i really appreciated your tutorial.. thanks for posting it.

nways, i used your tutorial in one of my school projects. i don't know how to use jquery yet so i copied all of your codes to my project. the mask is working well, however, the login box doesn't appear. everytime i click my login button, the mask covers my page but no login box appears on top of it. what seems to be the problem.?

i'm so noob at this. hope you can help. tnx!
april on 28 May 2009 says:
i forgot to mention that i have separated the codes.. separate file for javascript and css.

i just call both in my html page.
kevin on 28 May 2009 says:
Hi April, have you tried the one from the download link? it works.

Which browsers were u using?
april on 28 May 2009 says:
i have downloaded your codes and your demo works fine too. but it doesn't work on my project.

i just feel separating the javascript codes and the css as well so that my html page is clean to look at.

i'm using firefox version 3
kevin on 28 May 2009 says:
@april: alright, the script should work even tho the css and js separated. You will have to debug it, and find the cause.

1. make sure the class name is correct and not conflict with other class names.
2. make sure the z-index is correct, the popup menu should have the highest value.

if you can show me your work, that'd be even better :)
april on 28 May 2009 says:
already fixed it! just went down on all of the codes and found the problem. silly me, so careless.lolz

nways, i have a new dilemma. in my modal login form, i've set an error message right next to my input incase the user inserted a wrong username or password. but whenever i insert a wrong username/password., the modal box dissappear without showing the error message. and when i click the button to show the login box, the error is there. and so as the username and password i inserted.

is there any way to prevent the modal box to dissappear? unless the user clicked on a close button or on the mask.
kevin on 28 May 2009 says:
@April: great! you solved it. What was the problem?

how do you validate the username and password?
april on 28 May 2009 says:
i used php to validate my username and password. which is saved at mysql.
kevin on 28 May 2009 says:
@april: arr, this a bit tricky. After you clicked on the submit/login button, it navigates to another page? or do you use ajax to validate it?

you can always call the modal window using onload function, I have described it on the top.
Eshban on 28 May 2009 says:
HI,

I want to load a modal window on Page load instead of clicking on a link.


Kindly help how can i do this.

Waiting for reply
kevin on 28 May 2009 says:
@Eshban: I have already put the script and demo, please read the tutorial.
april on 28 May 2009 says:
here's the scene.. hope i could describe this well. in my index page.. i have this login button which activates the login modal box. the login button works, the box appears. inside the box i have a form with two inputs(username&password) and a button that acts as a submit, this activates the validation of the username and password.
besides these two inputs are error messages that appears whenever a user inputs a wrong password.

if the user inputs the correct username and password, the modal should dissappear and back to the index page, at this point, the user is already logged in. i have a session for this.

to be continued...
april on 28 May 2009 says:
now my problem is, if i insert a wrong username, the modal box dissappears. what i wanted to happen is that, when a user input a wrong username, the modal box won't disappear but instead show the error message and wait for the user to either click on the mask or insert another username again.

is my explaining confusing?! sorry for that.
kevin on 28 May 2009 says:
@april: this involves the way u validate the user. do you using ajax or just normal POST method to a php file?

If you're using ajax, you will need to cancel the submit button's default behavior if the user is invalid.

If you're using php, because the page need to be refresh/navigate away, I think what you can do is, show the modal window using onload=launchModal(id)

if, none of the above describes your situation, you will have to show me your website :)
april on 28 May 2009 says:
i'll try your php method.. hope it works! tnx kevin! your great knowledge in this is really a big help! =)

i'l be back soon to update you. gotta have some lunch first. i'm really hungry. lolz
april on 28 May 2009 says:
i'm really having a rough time with this.. sigh. still no improvement.
kevin on 29 May 2009 says:
@april: please use the contact me form for further discussion. I guess we're flooding this post. :)
tabby on 1 Jun 2009 says:
i would like to validate a form but the msg of validation should be displayed in jquery modal window...can anybody help me with this
empe on 4 Jun 2009 says:
hi kevin

i got same problem with Markvoce


Markvoce on 26 Mar 2009 says:
Yes the idea would be for the modal window to appear in the middle, no matter where the page is scrolled to. Cheers

i'm using your updated code, but there is the problem :(

would you like to help me, please
kevin on 4 Jun 2009 says:
@empe: Is the live demonstration working? I have tried both in IE6, Firefox and Chrome... it's all working... what browser and OS are you using?
empe on 5 Jun 2009 says:
i solved the problem!

i believe it is because doctype of my html

you can use script from http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
poompah on 11 Jun 2009 says:
Is it possible to use a timeout javascript to fade out a modal?

For example, an information modal pops-up and stays for 4 seconds before fading. No need for the use the click close. I have seen this elsewhere on modal boxes, can we do that here too?

Everything else is fine with the script :o)
kevin on 12 Jun 2009 says:
@poompah: yes, I think you can do that by using settimeout function and call the modal window function. I haven't tried it, but please let me know how it goes!
djzaa on 17 Jun 2009 says:
Thanks.
vampires on 17 Jun 2009 says:
Very nice
John Galt on 17 Jun 2009 says:
Great!

Added to http://tutlist.com
Leonardo on 19 Jun 2009 says:
Gracias, su código está cool!
jockep on 22 Jun 2009 says:
Is there any other way to use this method but don't need to make new div for every popup window, now i need to make new div with same settings for every window i want
kevin on 22 Jun 2009 says:
@jockep: unfortunately, it'll be hard to mod this script to accomodate ur request. I'll be doing a modal window revisit tutorial, but I can't tell you exactly when it will be published. All the best.
jockep on 23 Jun 2009 says:
Okey thanks for this script anyway, Will be visiting often, i love all jQuery stuff here
mr.T on 7 Jul 2009 says:
I don't have polish letters in




it's wierd because there is no problem on the rest of website
mr.T on 7 Jul 2009 says:
...in div id="boxes"
Rick Faircloth on 9 Jul 2009 says:
Hi, Kevin...just found your tutorial. Nice...
I'm enjoying building my own modal windows now instead of always using someone else's.

I was wondering if you've noticed a problem (not with your code) but with IE8 and fadeIn(). I'm put a spot in my modal window to fade in an error message and it works find it IE7 and FF3, but not IE8.
Tapeten online on 12 Jul 2009 says:
Hey, your Tuturials are really great !!
elmarko on 18 Jul 2009 says:
Hi, do you know how to set it so the modal window appears on top of a swf? Currently, it get's hidden under the swf in most browsers except ff3.5 and safari4 on the mac
elmarko on 18 Jul 2009 says:
Never mind. Figured it out!

http://www.alohatechsupport.net/webdesignmaui/maui-web-design-articles/layer_flash_under_html.html
Erwin on 28 Jul 2009 says:
Hi Kevin,

just the thing I was looking for! Thanx! Just one question... I am designing a website with a one-page layout. At the bottom there are buttons to launch a modal window. After pressing one of the buttons the window opens at the top of the page, so I have to scroll to see it. Is it possible to open the window otherwise?

Greetings,
Erwin
kevin on 28 Jul 2009 says:
Hi Erwin, that's a good point, you can do it by getting the scrollback offset, then recalculate the top position. However, it's a bit tricky because IE uses different functions to get the value. So, what you need to do is, replace the following code with line 24 (line number based on tutorial above)

var y=0;
if (self.pageYOffset) // all except Explorer
{
y = self.pageYOffset;
}
else if (document.documentElement && document.documentElement.scrollTop)
// Explorer 6 Strict
{
y = document.documentElement.scrollTop;
}
else if (document.body) // all other Explorers
{
y = document.body.clientHeight;
}

//Get the window height and width
var winH = y;


and it should work the way you want.
Erwin on 29 Jul 2009 says:
Hi Kevin,

Thanx for replying! Changed the code, the window now opens in the exact middle of the page (instead of the top), but i still have to scroll to see the window.

I want to use multiple modal windows, and the buttons to open them are spread over the entire page. Is it possible to specify coordinates for each window?

Greetings
Erwin
kevin on 29 Jul 2009 says:
Hi Erwin, I think I missed something... please replace

var winH = y;

with

var winH = y + $(id).height();

Try to use it in different position, it'd work... :)
Erwin on 29 Jul 2009 says:
Hi Kevin,

Again thanx for your reply! Changed it, but I think I'm still missing something because the modal window still opens in the middle of the page.

I have my design up and running on www.erwinnijhoff.nl. As you can see it's a one page layout I am designing for my Aikido club. It has got an auto scroll funcion. At the bottom the are two links, 'Aikikai organisaties' and 'Sponsors'. These are some of the buttons I want to assign modal windows to. If you click them you will see the modal window opening in the middle of the page. It would be great if the window opens in a way you could see it immidiately.

Hope you can help, because as you will have noticed I am not a Javascript expert... (at all)

Greetings,
Erwin
kevin on 29 Jul 2009 says:
@Erwin: hey, i know what's the problem... my bad, so, this is the working solution:
replace this

var winH = y + $(id).height();

with

var winH = y;


and then, replace this:

$(id).css('top', winH/2-$(id).height()/2);

with

$(id).css('top', winH + $(id).height());

you see, the height is being divided by 2, that's y it appears in the middle of the page. :) Cheers.
Charlie on 3 Aug 2009 says:
Hi there Kevin! This is wonderful code. I'm having a bit of trouble trying to place images on top of the window after it opens. I currently have my code setup to run my jquery plugin when the modal window opens, but once it starts pulling the pictures from TwitPic, the modal window disappears. Do you have any ideas?
kevin on 4 Aug 2009 says:
Hi Charlie, Thanks, but I have not tried it with TwitPic, it could be a conflict :(
Brian on 6 Aug 2009 says:
Hi Kevin, great stuff! However, if I call a page to an iframe, and that page has a javascript function, once the javascript is activated, the key press (in this case set to 27 (esc), does not close the modal. The other methods - click the surround & 'close' - work fine. Any ideas? Otherwise, I think it is brilliant!
Brian on 6 Aug 2009 says:
.... further to the above, I have found that if you click within the iframe - even one with no javascript, just plain old html, the effect is the same - the key press to close the modal doesn't work
Do I need to change my options and not offer a key press in these cases?
kevin on 6 Aug 2009 says:
hmm, haven't try that in iFrame, did a rough search online, not sure if this will work,
http://forums.asp.net/t/1365548.aspx

otherwise, you will have to remove it.
Brian on 7 Aug 2009 says:
Thanks, Kevin - no joy unfortunately, so the key press close will have to go. I guess it is asking toooo many things to talk to each other!

Small price to pay for a great jquery opportunity - thanks again
Sean on 7 Aug 2009 says:
Thanks so much for this! I know you can load the window when the page loads as I grabbed the code you posted above for this. I was just wondering if there is a way to only load it the first time they come to that page and again if they refresh the page?
Mhor on 9 Aug 2009 says:
@kevin: Thank you for this code. I'm currently using it on our project. Thanks to you again.

But there is one thing, I'm currently using IE6 (i hate IE6 but this is what our client demands us to support so we have no choice) and my screen consist of combo boxes and a link to the modal window. The problem is, whenever I load the modal window, the modal window works perfectly but the combo boxes from my parent window still appears (not affected by the #MASK div).

Any advice on this?

Thanks again.
Mhor on 10 Aug 2009 says:
@kevin: Another question, after I display the modal window. I tried to maximize the screen (assuming the screen is not maximized at first). The problem here is, I want the modal screen to remain center and the whole screen at the back be covered (dark gray) after I maximize the screen.

Any advice?

Thanks
kevin on 10 Aug 2009 says:
hi Mhor, for the first answer, I think you have z-index set for the combo boxes. Or, maybe you can increase the z-index of the mask.

for the second issue, you can use:

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

//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);

});

it will be something look like about, you need to set the id thou.
kevin on 10 Aug 2009 says:
@sean: there is one way to do it. it's using cookie. I'm never really set cookie with javascript before, but I can tell you the idea. So, this is how it works:

You need a script that able to create and detect cookie. If user is first time visitor, your script will search for the cookie, if no cookie was found, launch the window and create a cookie, so that next time when the user visits your site, you script will pick up the cookie and not to launch the window.

the window will popup again if the user cleared the cookie. :)

hope it helps.
Mhor on 10 Aug 2009 says:
@kevin: Thanks for answering my question...the 2nd issue was fixed but not the first, Actually, this problem occurs only in IE6. I don't know why (that's why I don't like IE6 = buggy). I've tried setting the z-index for combo box and even increased z-index for #mask, but I still doesn't work.

Any ideas on this?

P.S. Actually, an alternative solution to my problem was to hide and combo box everytime I click my modal link and show it again when my modal is closed. But I don't think this could be a good solution. If there's a way I could hide the combo box only when I'm using IE6, that might be better i think.
kevin on 10 Aug 2009 says:
@Mhor:... hmm, that's weird... try set the combobox or the parent of the combobox position to absolute or relative, z-index only work with those position. by default, all the elements that have no z-index should appear underneath of the mask.
Mhor on 10 Aug 2009 says:
@kevin: Another question, after I display the modal window. I tried to maximize the screen (assuming the screen is not maximized at first). The problem here is, I want the modal screen to remain center and the whole screen at the back be covered (dark gray) after I maximize the screen.

Any advice?

Thanks
Mhor on 10 Aug 2009 says:
OOPPPSS...wrong send...kindly erase the above post of mine.

@kevin:

Yes, it is really wierd...i tried the both of the position attributes (style="position:absolute;" / style="position:relative;") on my combo box and it still doesn't work. I'm sorry for causing you too much trouble.

Here is my combo box code
(I am using smarty for enlisting the options. You can remove the smarty thing and replace it with ordinary HTML codes if you want to test it):


{foreach from=$SEARCH_FIELD key=arr_id item=curr_item}

{$curr_item.option_lbl}

{/foreach}

Mhor on 10 Aug 2009 says:
@kevin: sorry for spamming too much...i think this comment removes html tags.
(removed "")

select name="cmb_search_fields" id="cmb_search_fields" style="width:182px; position:relative; z-index:0;"
Ryan on 11 Aug 2009 says:
Is there a way to alter this code (dialog2) so we can have multiuple links on one page, all opening the an iframe inside the modal, that will goto different pages? ie: iframe src='display.php?pid=1' ? I hope that makes sense. Really, i just want to pass an id or something to the iframe..
Jonathan on 12 Aug 2009 says:
I want to use the script to open a modal window to display a large image. Problem seems to be when the image is larger than the parent page. Scroll bars do appear (in Firefox - not tested anywhere else) but the background mask does not extend beyond the original screen, plus the modal window disappears above the top of the browser window (because it's fixed in the center of the page before the modal window opens and the page expands).

Check out what I mean here:
http://www.art411.com/modal/jquery-modal-window.html (URL will not persist when issue solved - sorry)

Any ideas?
Jonathan on 13 Aug 2009 says:
okay - so a few hours thought and I have it solved - need to manipulate:

$(id).css('top', winH/2-$(id).height()/2);

and:

$('#mask').css({'width':maskWidth,'height':maskHeight});

Please delete my two posts.
Sammy on 16 Aug 2009 says:
Hi Kevin,
It was a nice one! I started digging into jQuery recently and i loved it so far.....I ran into a problem though and wanted to share with you experts!
I have an event calender with events populated from Database and on clicking the events i am able to show a jQuery popup window with the event details.
But how can i pass the date that the user clicked to jQuery in order to show the events on that particular day?

I hope this makes sense......Any help in these lines would be greatly appreciated.

Thanks,
Sam.
hapleng on 17 Aug 2009 says:
i like html
Ryan on 24 Aug 2009 says:
Never mind, I worked it out
Quenton on 24 Aug 2009 says:
Sweet code. Thanks a lot!
Quenton on 24 Aug 2009 says:
A quick question that maybe someone has an answer to.

The first time I open the modal window the screen goes completely black and then fades to a dark gray. If I close the modal window and reopen it, it just fades to dark gray as it is supposed to. Any ideas?
mp3 on 25 Aug 2009 says:
Hi, interest post. I’ll write you later about few questions!
hjkhk on 27 Aug 2009 says:

Thanks for posting, I really enjoyed your most recent post. I think you should post more often, you obviously have natural ability for blogging!
Enrico on 29 Aug 2009 says:
Many thanks for your post! The code is at the same time simple and great ;)
Phpando on 3 Sep 2009 says:
With the current code to resize the page, even if the window isn\t open, the fadeIn is given in the mask.
What to do?
Paulo on 8 Sep 2009 says:
I m trying to add a link for a second popup in the first one. I would like when the user click in the link close the popup and open another one.
I am not getting there. Do you know how can I achieve that? Thanks a million
edie on 11 Sep 2009 says:
Hey this is great thank a lot main
sheila on 11 Sep 2009 says:
Thanks a lot for this example.Can you please give me a another example where a base page p1 opens a modal window w1 and w1 opens another modal window w2 and should be able to pass values(maybe a value entered in textbox) from w2 -> w1 -> p1. Thanks in advance
kevin on 13 Sep 2009 says:
hi sheila, you can do that.. i did that before, what you need to do is, in the modal window you create three content DIV with different form section, hide the last two and display the first one. then, create a button that will hide the first and third and display the second. Just hide and display.
Shir on 29 Sep 2009 says:
Hi, any chance of adding sound (mp3 / wav) when the window shows up?

Thanks
Gary on 3 Oct 2009 says:
Your window works great! Im new to jquery. i put my test window on a page with some embedded flash and everything but the flash masks out. Why does this happen and how might I fix it? Thanks
John on 17 Oct 2009 says:
Thanks a lot, easy to use and edit :)
download mp3 free on 27 Oct 2009 says:
Information is very useful.
dr.emi on 3 Nov 2009 says:
awesome another ThickBox !
thank you!
Carlos on 3 Nov 2009 says:
VERTICAL CENTERING: First off, thanks for the great tutorial, it will come in handy in the future on all my projects. I did spend some hours trying to figure out how to center the window vertically as I see many out there are. I found a solution that worked great (don`t know if it`s the best but it works) and just wanted to post it to save some of you some time as well, thanks again:

Change:

$(id).css(`top`, winH/2-$(id).height()/2);

to:

$(id).css(`top`, parseInt( winH/2-130) + $(document).scrollTop() );

That`s it, hope it helps some of you.
Kumar Desai on 15 Nov 2009 says:
ive been trying to get the modal window to work on a page that also uses jqueryui library especially sone sliders. However the sliders disappear when I connect to: http://code.jquery.com/jquery-latest.pack.js
and the modal windows dont work when I try to connect to a local version of jquery.

heres the page: http://www.coolmartian.com/projects/primarq/FINAL/offerings.php

Click the Create new button for the modal. it doesnt work. any ideas?
simplyseth on 20 Nov 2009 says:
Im using the above code to open a popup with a form in it.

1> I would like for it to not close when I hit submit.

2> Not mask the whole screen when the popup opens.

the form I have uses an ajax post.
Ubuntu-Dude on 24 Nov 2009 says:
uhm, thanks for sharing the tuts. i tried the copy in clipboard, but it just alerts me with \"copied in clipboard\", but really isnt there. uhm, im using gchrome.
babu on 25 Nov 2009 says:
hai,
thank you for providing this details. this is very useful for me.
regards
http://www.srisoftwarez.com
Shahriar Hyder on 30 Nov 2009 says:
Nice one mate. I have also added the link to your post in my Ultimate collection of top jQuery tutorials, tips-tricks and techniques to improve performance. Have a check below:

http://technosiastic.wordpress.com/2009/09/24/collection-of-top-jquery-tutorials-tips-tricks-techniques-to-improve-performance/
download mp3 on 3 Dec 2009 says:
Thank you for good information
ad-no1 on 6 Dec 2009 says:
Thank you for this great tutorial.

Is there a way to put in an iframe into the window where the src in the iframe is a \" + source + \" which will be picked up from the <a> tag.
indialike on 16 Dec 2009 says:
Very nice and useful tutorials to web designers,
Thanks for posting.
akam on 27 Dec 2009 says:
I love this kind of code,,,
good job
nphp101 on 29 Dec 2009 says:
Really nice jQuery Scripts. I will give a link to my blog! Thanks!
healthy on 9 Jan 2010 says:
Everything is ok now. It works very well.
Ed on 13 Jan 2010 says:
Very nice and useful tutorial, thank you. One question: Did you know the user can still tab through the elements and activate them with the keyboard?
jeffery on 17 Jan 2010 says:
great work my friend...

this tutorial has been simple and easy to understand...

keep this good work up.....

hoping more tutorials of using jquery.....

once again thanks for sharing this wonderful work.......
lawless on 21 Jan 2010 says:
Thanks for the code. Got it up and running using the onLoad function.

Quick and easy, great work!
Milan on 31 Jan 2010 says:
Why click from other jQuery functions doesn't work? For example, I have some if function which check what browser is used and display diferent link based on browser type, but those modal won't open. If I copy that same link elsewhere everything works.

Example code:

<code>
<script type="text/javascript">
$(document).ready(function(){
if ( $.browser.browser()=="Internet Explorer")
{
$('#test-browser').html( '<a href="#dialog" name="modal">Open modal</a>' );
}
else
{
$('#test-browser').html( '<a href="#dialog1" name="modal">Open modal</a>' );
}
});
</script>
</code>
izlesene on 3 Feb 2010 says:
everything works good
Surya on 4 Feb 2010 says:
Hi I have some problem with this popup window. I used this poppu to modify the info. After the modification I want to close the window from that event, I couldn't close it. Can you guide me in this issue.

Thanks
Surya
patty on 5 Feb 2010 says:
This was great. Thank you!

Leave a comment

http://
Subscribe RSS Subscribe RSS, Keep yourself updated with queness latest posts!
Pixel Crayons Buy and Sell Flash Buy and Sell Flash

Buy wholesale computers directly from China at DHgate.com

Discover the tools to build your e-Commerce Site with Netfirms

  •  
  •  
  •  
  •  
  •  

Community News

Recent Comments

Random Posts


View all posts and news Back to top

About the Author

A web designer and developer who is passionate and keen on contributing to the web development industry. Feel free to say hi to me, or follow me on twitter.

Kevin Liew

Partner

  • Web and Designers
  • CSS Style
  • PV.M Garage Blogzine - (Italian)
  • TutsValley
  • Designrfix
  • CoolVibe
  • Web Developer Juice
  • Denbagus
  • Web Hosting Secret Revealed
  • PSD to HTML Conversion
  • BlueHost