UserIsCorrupt
UserIsCorrupt

Reputation: 5025

.hide on any click action not relating to child elements

<div id="example" style="background:yellow;height:200px;width:200px;">
 <button>Some text</button>
</div>​

I want #example to .hide when it's clicked, but I don't want it to .hide when it's child elements get clicked.

Upvotes: 0

Views: 48

Answers (1)

Joseph
Joseph

Reputation: 119867

Add a handler to the <div> and then check if it's the target.

In this example, the event.target is the element that was actually clicked, but this is the element attached with the handler.

$('#example').on('click', function(event) {
    if (event.target === this) {
        alert('div, not button');
        $(this).hide();
    }
});

Upvotes: 3

Related Questions