Randy Gonzalez
Randy Gonzalez

Reputation: 445

Ignore child elements using jQuery event delegation

I am using the on method to delegate a click event to injected divs. These injected divs will have child divs as well that are positioned outside of their parent div. I am looking to ignore the click event on the child divs but can't seem to figure it out. Here is an example:

Here is a Fiddle: http://jsfiddle.net/7ULUJ/

Here is the HTML

<div id="container">
<div class="click_this_one_only">
    click event delegated
    <div id="child1">
        child 1
    </div>
    <div id="child2">
        <div id="child_child">
            child child
        </div>
    </div>
</div>
</div>

Here is the jQuery:

$('#container').on('click', '.click_this_one_only', function() {

   alert('you just clicked .' + $(this).attr('id'));
});

Upvotes: 0

Views: 682

Answers (1)

Esailija
Esailija

Reputation: 140228

Check the event target for the element:

http://jsfiddle.net/7ULUJ/3/

$('#container').on('click', '.click_this_one_only', function(e) {
    if ($(e.target).hasClass("click_this_one_only")) {
        alert("clicked");
    }
});​

Upvotes: 3

Related Questions