user1452893
user1452893

Reputation: 868

Why won't this div close when I click on the link which opens it?

Here's the fiddle.

The code includes:

$('.icon').click(function () {
    $('.foo').toggle();
});
$(document).mouseup(function (e) {
    var container = $('.foo');

    if (!container.is(e.target) // if the target of the click isn't the container...
    &&
    container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.hide();
    }
});

I can use the link to open it, the codes closes it when one clicks outside of it but I can't close it with the link that opened it initially.

Upvotes: 2

Views: 153

Answers (2)

Wex
Wex

Reputation: 15695

You're missing the check in your if statement to see if .icon is the target.

http://jsfiddle.net/gT5BT/100/

var foo = $('.foo'), icon = $('.icon');

icon.click(function () {
    foo.toggle();
});

$(document).mouseup(function (e) {
    if (!foo.is(e.target) && !icon.is(e.target) && !foo.has(e.target).length)
        foo.hide();
});

Upvotes: 1

twil
twil

Reputation: 6162

You hiding and showing it again. Just comment container.hide(); and try clicking .icon

To overcome this issue just check for .icon container in global mouseup event handler. http://jsfiddle.net/55DSp/

Upvotes: 4

Related Questions