Search code examples
jqueryjquery-eventsevent-bubbling

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.


Solution

  • 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 {
    
        }
    });