Ben
Ben

Reputation: 171

How to disable click events on a parent DOM object without disabling click events on its child DOM object?

I have some HTML like this:

<a class="button">
    <span>
        <span>
            <span class="buttonspan">Content</span>
        </span>
    </span>
</a>

I already have some events on the parent Anchor object. Now I am trying to add a click event on to the child span element and at the same time to disable click events on the parent Anchor object. I am using jQuery to achieve this, but I could not figure out. My jQuery code is like this:

$('a.button').click(function(event){
    return false;
});

$('.buttonspan').live('click', function(event){
    event.preventDefault();
    event.stopImmediatePropagation();
    // some function
});

If I execute the code above, it prevents the child element click event as well. But if I do not the first part, the parent click event will be triggered as well. Is there a way to disable the parent event without disabling the newly added child click event?

Upvotes: 1

Views: 4242

Answers (1)

dcharles
dcharles

Reputation: 4852

You could set the click event on the parent button and use the event target to determine what was clicked and perform the necessary actions.

$('a.button').click(function(e) {
    var $target = $(e.target);

    if ($target.is('.buttonspan')) {
        // do actions for the .buttonspan click
    } else {
        // do actions for a click anywhere else inside a.button
        e.preventDefault();
    }
});

Upvotes: 3

Related Questions