Jon
Jon

Reputation: 8521

Cannot Bind Event Listener to Dynamically Created Elements

I'm trying to add an event listener to dynamically created elements, but am having trouble doing so. In my code below, I can never detect that <p> has been inserted so I never see the console message Bar Inserted. Am I doing somethign incorrectly?

http://jsfiddle.net/3msVK/

    $('#button').click( function() {
        $('#foo').append('<p>foo</p>');
        $('p').append('<p>bar</p>');
    });  
    $('#foo').bind('DOMNodeInserted', function() {
        console.log('Foo Inserted');
    });  
    $('p').on('DOMNodeInserted', 'p', function() {
        console.log('Bar Inserted');
    });    

    <div id="foo">Foo</div>
    <div id="button">BUTTON</div>

Upvotes: 0

Views: 562

Answers (1)

bobthecow
bobthecow

Reputation: 5117

When you first attach the listeners, $('p') doesn't select anything (since there isn't a p on the page yet). You should attach the listener to the parent, #foo:

$('#button').click( function() {
    $('#foo').append('<p>foo</p>');
    $('p').append('<p>bar</p>');
});  
$('#foo').bind('DOMNodeInserted', function() {
    console.log('Foo Inserted');
});  
$('#foo').on('DOMNodeInserted', 'p', function() {
    console.log('Bar Inserted');
});    

<div id="foo">Foo</div>
<div id="button">BUTTON</div>

Upvotes: 1

Related Questions