markzzz
markzzz

Reputation: 47945

How to "not handler" a click from a children element

This is my code :

HTML:

<div id="container">
    <div id="box">
        Content
    </div>
</div>​

CSS:

#container
{
    position:relative;
    width:400px;
    height:400px;
    background-color:red;
}

#box
{
    position:absolute;
    width:200px;
    height:200px;
    top:100px;
    left:100px;
    background-color:blue;
}
​

jQuery :

$('#container:not(#box)').click(function (e) {
    e.preventDefault();
    $('#container').fadeOut(300);
});​

I want to fadeOut only clicking on the parent (the red div). If I click on the blue one (the child) nothing should happens. How can I do this with jQuery? tried with :not but seems this is not the right solution...

Upvotes: 2

Views: 921

Answers (3)

Miqdad Ali
Miqdad Ali

Reputation: 6147

$('#container').click(function () {
    $('#container').fadeOut(300);
});

$('#box').click(function (e) {
    e.stopPropagation()
});

Upvotes: 0

Richard Neil Ilagan
Richard Neil Ilagan

Reputation: 14747

When you click on the #box, the click event also registers on the parent #container element because the event bubbles up.

There's two ways top-of-head to prevent that.

First is to stop the bubbling from happening. You do that by calling e.stopPropagation() on the #box click handler. But, of course, you've got no #box event handler, so the next one is a bit more attractive.

Second is to check from the #container event handler whether or not you're clicking the actual #container or some child and that the event just bubbled up. You can do this by inspecting the e.target element, and comparing that to this in the #container event handler.

Upvotes: 3

Matt
Matt

Reputation: 75317

All you need to do it check whether the element the event originated from (e.target) is the #container (this):

$('#container').click(function (e) {
    if (e.target === this) {
        $('#container').fadeOut(300);
    }
});​

Upvotes: 6

Related Questions