Handling events in elements added later

Asked

Viewed 123 times

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>'

Rotate on Jsfiddle and check: http://jsfiddle.net/dpa8rj8L/

In Button1 the event is triggered. Not in Button2, because it was added later.

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

1 answer

4


  • 1

    It worked. Updated version of Jsfiddle for anyone who wants to check out: http://jsfiddle.net/dpa8rj8L/7/

  • 1

    Just to complement the answer, this is delegation of events in jQuery.

  • Thanks, @Danguilherme, I updated the answer with the link, Perfect :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.