Aaron
Aaron

Reputation: 1966

jQuery: fadeOut only when parent div is clicked

jQuery

$(".window-container").click(function() {
    $(this).fadeOut("fast");
});

HTML

<div class="window-container">
    <div class="window-wrap">
        <div class="window-content">
             asdf
        </div>
    </div>
</div>

I have a link that makes window-container and each child div appear. (Like a Facebook popup)

To close window-container I want to be able to click anywhere except within the window-content div. Because if I have an input contained within, and I focus on it, it will close everything.

So how can I have it only close if a user clicks the window-container or window-wrap divs?

Upvotes: 2

Views: 519

Answers (3)

Aram Mkrtchyan
Aram Mkrtchyan

Reputation: 2700

$(".window-container").click(function (e) {
        $(this).fadeOut("fast");
        e.stopPropagation();
    });
    $(".window-wrap, .window-content").click(function (e) {
        $(".window-container").css("display", "block !important");
        e.stopPropagation();
    });

    $("body").click(function () {
        $(".window-container").fadeOut("fast");
    });

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359786

Just check event.target to make sure the click event originated from div.window-container or div.window-wrap.

$(".window-container").click(function(e)
{
    if ($(e.target).is('div.window-container, div.window-wrap'))
    {
        $(this).fadeOut("fast");
    }
});

Alternately:

$(".window-container").click(function(e)
{
    if ($(e.target).has('div.window-content').length)
    {
        $(this).fadeOut("fast");
    }
});

Upvotes: 3

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

Best way is to stop the propagation of the event (with event.stopPropagation()), when it is initiated from inside the .window-content element.

$('.window-content').click(function(e){
   e.stopPropagation();
});

This way the click event will never reach the .window-container element.

Upvotes: 0

Related Questions