Gerardo
Gerardo

Reputation: 1948

click() assigned in document.ready in jQuery

Do assignments in document.ready (click(fn) specifically) apply to newly appended elements that match the selector?

If not, how can I assign it to this new elements? Do I have to write the assignment after every append or is there a better way?

Upvotes: 3

Views: 3517

Answers (1)

Paolo Bergantino
Paolo Bergantino

Reputation: 488464

You are looking for the live functionality. Per the manual:

Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.

So if you do this:

$(document).ready(function() {
    $('div.test').live('click', function() { alert('yipee!'); });
    $('body').append('<div class="test">Click me!</div>');
});

When you click on the div you will get the alert even though it was added after the event was bound.

Upvotes: 7

Related Questions