Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 235
Gerardo Avatar asked Nov 20 '25 00:11

Gerardo


1 Answers

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.

like image 125
Paolo Bergantino Avatar answered Nov 22 '25 13:11

Paolo Bergantino