Arsen Kazydub
Arsen Kazydub

Reputation: 5660

jQuery on() for dynamically added elements, which use stopPropagation()

Suppose, we have a few dynamically added <div /> on a page, and we need to bind a click event to each of them. Normally, we would use:

$(document).on( 'click', 'div', function() {
    // ...
});

But I need to prevent bubbling up, after these divs have been clicked. So I'm trying to use:

$(document).on( 'click', 'div', function( e ) {
    e.stopPropagation();
    // ...
});

This doesn't work, because the click doesn't reach the document element. I miss live() function, because it could bind events directly to new elements, not to the document.

So how can we make this work? Thank you in advance!


Update

I've found the problem. As Ninsly wrote, the event did reach the document element.

In my app there're a lot of ajax, and I have 2 functions, that are bound to these divs.

The 1st one has the code, that I posted above:

$(document).on( 'click', 'div', function( e ) {
    e.stopPropagation();
    // ...
});

The 2nd one is bound after a div is already on the page, so I used:

$('div').click( function( e ) {
    e.stopPropagation();
    // ...
});

The 2nd one worked, the 1st one - did not. I tried to rewrite the 2nd function in the same way as the 1st one - all works fine now.

Upvotes: 1

Views: 908

Answers (1)

Bojan Petkovski
Bojan Petkovski

Reputation: 6933

return false; will do the trick on this case.

It is the same as writing

event.preventDefault();
event.stopPropagation();

It will prevent the default action for the event and will stop the event bubbling up through the DOM :)

Upvotes: 1

Related Questions