Dealing with events in elements added later

2

Consider the following HTML:

<div id="div">
    <button class="foo">Botão1</button>
</div>

And the following script:

$(".foo").click ->
    alert "foobar"

$("#div").append '<button class="foo">Botão2</button>'

Run JSFiddle and check out: link

On Button1 the event is triggered. On Button2 no, it was added later.

I would like to know how best to make the event available for the second button, if possible, without having to add the click event again.

    
asked by anonymous 11.09.2014 / 14:42

1 answer

4

When the element does not exist in the DOM , you have to do the delegation of the event in document , or in a more element next that includes the .foo 's:

$(document).on( 'click', '.foo', function(e){ 
    alert('bar');
});
    
11.09.2014 / 15:00