views:

310

answers:

1

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?

+1  A: 

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();
    }
});
Marve
Maver, thanks a lot for your quick reply. It seems this one works when I click on the dom object, but what if I use jQuery trigger method to programmatically trigger the click event. For example: $('.buttonspan').trigger('click');. It seems it does not work in this case.
Ben
It should still work when the click event of .buttonspan is programatically triggered. I just did a test of this to be sure and it did indeed work properly.
Marve
Yah, Marve, there was some other issue. Your solution works! Thanks!
Ben