tags:

views:

22880

answers:

2

I'm trying to make a modal dialog in the least amount of jQuery code as possible because my project already has a bit too much jQuery loaded into it.

So, I first needed an overlay, which is achieved with:

$('body').wrapInner('<div />')
.css('opacity','0.5')
.css('z-index','2')
.attr('id','dim1');

Disregard for now that I have another routine to kill the click events on #dim1 while this modal is present. So, now I need to draw my modal dialog on top:

$('body').append('<div id="test">My Test</div>');
$('#test')
.css('opacity','1.0')
.css('position','fixed')
.css('color','#000')
.css('z-index','2000')
.css('height','300px')
.css('width','300px')
.css('top','50%')
.css('left','50%');

However, when I do this, I end up with a dimmed out #test, when I don't want that to be dimmed -- just the stuff behind it. What's the trick?

+3  A: 

I think your best solution might be to use a jquery plugin. A quick google search threw up this: http://www.ericmmartin.com/simplemodal/ which is doing what you need in three lines!

If you want some more, there are loads on the jquery overlays plugin page

From the look of it, the CSS is the key to getting things right, and most of these examples should come with demo CSS for you to adapt.

Obviously this brings in more external jquery code which you are concerned about - but I would suggest a well written and stable plugin would save you lots of work/time/lines of code!

Jennifer
+8  A: 

See this quick demo here, the key lies to the modal being absolute over the top of the opaque background. The demo dynamically adds the background overlay div and the modal div to the body but you could define these in the html and just show them.

Agreed there is no need to use a plugin for a modal effect, most of the plugins come with lots of options hence the bloat which you do not want if you only need the simplest of effects. - Note we can do this in two lines rather than 3 - and without a plugin!!

Also it is far easier to define css classes and add these rather than add inline styles to an element in script. Easier to maintain.

redsquare
hmmm improved....mine was a quick demo not a full flung peice of functionality!
redsquare