jerome
jerome

Reputation: 4997

Event Bubbling and jQuery

I'm trying to capture a click event that bubbles up the DOM to the body, check to see what the selector of the click element is, and then based on that, choose to call a function.

Something like this:

<body>
    <a id="do-default-code">Default code</a>
    <a id="do-override-code">Override code</a>
</body>

And I'm picturing (psuedo-code) like this. I am using jQuery:

$('body').bind('click', function() {
    if ($(this) === $('#do-override-code')) {
        overrideCode();
    } else {

    }
});

I realize that I don't fully understand event bubbling in this context, and that the above code is not correct, so I am looking to the community for guidance.

Upvotes: 1

Views: 352

Answers (2)

Coin_op
Coin_op

Reputation: 10728

In your statement your this refers to the element that you have bound the event to. In this case the body element. Thus the if statement is never true.

So to get the element that you have actually clicked on you need to examine the target in the event object. Something like the following should work.

$('body').bind('click', function(event) {
    if ($(event.target).attr('id') == 'do-override-code')) {
        overrideCode();
    } else {

    }
});

Upvotes: 2

jcolebrand
jcolebrand

Reputation: 16035

You'll need to pass in the event on your function and check the event.

This link gives all the information you could want to know http://www.quirksmode.org/js/events_properties.html such as

Which HTML element is the target of the event?

from which you can easily extract whatever semantic info you wanted

Upvotes: 0

Related Questions