webprogrammer
webprogrammer

Reputation: 2477

jQuery on(): strange behaviour

This code works on my site:

$(function(){
    $('.link-follow-stop').on('click', function(event){
        console.log('|||');             
        return false;
    });
});

But this doesn't:

$(function(){
    $(document).on('click', '.link-follow-stop', function(event){
        console.log('|||');

        return false;
    });
});

I see no errors when running the second code sample on my site, but the console.log call does not fire when I click the .link-follow-stop link.

I tried running the second code sample at jsFiddle and it worked like I was expected. What can be wrong?

Link with class 'link-follow-stop' is static (I mean not dynamic).

Upvotes: 1

Views: 124

Answers (1)

Barmar
Barmar

Reputation: 780788

If you have a click handler on an element that contains .link-follow-stop and it uses e.stopPropagation(), this will prevent the event from bubbling up to document. The second form of .on() depends on the event bubbling up to the element that that handler is bound to; it then checks whether the actual target of the event matches the selector.

The following demonstrates this:

<div class="outer">
    <div class="inner">
        Click here
    </div>
</div>

$(function() {
    $(document).on("click", ".inner", function() {
        alert("inner");
    });
    $(".outer").click(function(e) {
        e.stopPropagation();
        alert("outer");
    });
});

FIDDLE

When you delegate with .on() you should bind the handler to the most specific static element(s) that contains the dynamic element. This minimizes the risk that another handler will interfere and prevent bubbling.

Upvotes: 4

Related Questions