ogni
ogni

Reputation: 327

Close Div overlay by clicking anywhere on the body

This is what I've done:

$('#keks-overlay').hide();  

$('#click').click(function(){
    $('#keks-overlay').toggle(450);
});

$('#close-overlay').click(function(){
    $('#keks-overlay').toggle(250);
});

​ jsFiddle: http://jsfiddle.net/rHKkD/22/

This works fine, but it shows/hides (toggles) only by clicking the "X" (#close-overlay).

I'd like do something like the fancybox-effect: fade out on clicking anywhere on the whole body.

Thanks for your help.

Upvotes: 0

Views: 6526

Answers (2)

CheeseWarlock
CheeseWarlock

Reputation: 1371

You can add an event handler to a div that contains the whole page (or the document itself), and hide() the overlay in that handler.

$("#somebody").click(function() {
    $('#keks-overlay').hide(250);
});

However, if you want to prevent clicks on the overlay itself from triggering the hide(), you could either add an event handler to the overlay that returns false (to prevent the event from bubbling up), or place the overlay outside the div that holds the rest of your content (which works because the overlay has absolute positioning).

I updated your fiddle to show the second method.

Upvotes: 1

Vincent
Vincent

Reputation: 103

try (when document ready)

var inoverlay = false;
$('#keks-overlay').hover(function() {
    inoverlay = true;
}, function() {
    inoverlay = false;
});

then fetch all clicks on the document, check the inoverlay variable, if it's false hide your overlay, else do nothing. If you have a button that opens the overlay in the first place, be sure to check that it's not that button that's being clicked when you intercept clicks on the document.

$(document).click(function(e){
    if(inoverlay && (e.target.attr('id') != buttonForOverlay.attr('id') )) {
        closeOverlay();
    }
});

Upvotes: 1

Related Questions