eric01
eric01

Reputation: 919

In jQuery, how can I fadeOut an overlayed div by clicking anywhere in the body?

I am making an image viewer. When I click on an image, it fades in the "overlay" Div with the image inside. But with the code below, when I click on the image, the div fades in but it immediately fades out without me re-clicking. What is wrong with me code?

I believe I need to put that "body click" line inside the first function but it doesn't work. How can I make such that this "body click" happens only after the overlay fades in?

Thanks in advance.

$('.pic').click(function(){
        $('#overlay').html("<img class='enlarged_pic' src='" + (this).src + "'>").fadeIn();
        }); 

$('body').click(function(){
        $('#overlay').fadeOut();
        });     

Upvotes: 2

Views: 1176

Answers (3)

Blazemonger
Blazemonger

Reputation: 92903

You need to add e.stopPropagation() to your first handler. What happens is that the click event is bubbling from your .pic up to the body, triggering both handlers when you only want one. .stopPropagation() blocks the event from bubbling any higher up the DOM.

$('.pic').click(function(e){ // don't forget that 'e'
    e.stopPropagation();
    $('#overlay').html("<img class='enlarged_pic' src='" + (this).src + "'>").fadeIn();
}); 

$('body').click(function(e){
    $('#overlay').fadeOut();
});  

http://jsfiddle.net/VQkNa/

You may also want to make it so that clicking on the overlay itself doesn't fade the overlay. This is easily done by detecting the target of a click:

$('body').click(function(e) {
    if (e.target.id !== "overlay") {
        $('#overlay').fadeOut();
    };
});​

http://jsfiddle.net/VQkNa/1/

Upvotes: 3

Beto Frega
Beto Frega

Reputation: 976

Try this out:

var isOverlaid = false;
$('.pic').mousedown(function() {
    $('#overlay').html("<img class='enlarged_pic' src='" + (this).src + "'>").fadeIn('slow', function() {
        isOverlaid = true;
    });

});
$('body').mousedown(function() {
    if (isOverlaid) {
        $('#overlay').fadeOut('slow', function() {
            isOverlaid = false;
        });
    }
});​

http://jsfiddle.net/XeNc8/

Upvotes: 0

Jonathan Payne
Jonathan Payne

Reputation: 2223

I would assume that both of your methods are being called.

When you click the '.pic' it calls the .fadeIn(); And also, because when you click '.pic' it is also on the body, it calls the .fadeOut();

I would try changing your selector on the body, to not include .pics.

Upvotes: 0

Related Questions