Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying jQuery .click() to Ajax-generated HTML

I'm using jQuery to manage the "Edit" button on comments for an app I'm coding. In my document.ready, I have:

$('.edit-button').click(function(){
// Code to trigger the editing interface for parent comment
});

I'm also using jQuery to display newly-posted comments without refreshing the page. Within the relevant $.ajax() function, I write the new comment to the DOM using a $.before(data). Problem is, the .edit-buttons within data don't have the aforementioned $.click() applied to them, because that happens in document.ready. So I click on them, and nothing happens.

I've tried the (extremely ugly) solution of having the Ajax function re-include the .js file in which I call document.ready. This works, except it re-applies the .click() to every single .edit-button, so they open the editing interface twice (or even three times).

So, how can I re-apply the $.click()s from document.ready? Preferably without having to copypasta my document.ready function into another javascript file, in case I modify it later.

like image 502
Zacqary Avatar asked Dec 09 '22 00:12

Zacqary


2 Answers

Depend on your version of jQuery, there are these solution:

$(selector).live(events, data, handler);                // jQuery 1.3+
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(document).on(events, selector, data, handler);        // jQuery 1.7+

obviously the last one .on() is the best choise. More Information.

but about .bind():

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. Reference

For your problem answer is something like these:

$('.edit-button').on("click",function(){  })

or

$(document).on("click", ".edit-button", function(){  }); 

Note: Use of the .live() method is no longer recommended since later versions of jQuery offer better methods that do not have its drawbacks. More Information

Update .live() removed after jQuery 1.9 upgrade

like image 123
Iman Avatar answered Jan 01 '23 12:01

Iman


Try this

$('body').on("click", ".edit-button", function(){

})

you might be able to change the body selector with something more targeted.

like image 34
Emil Avatar answered Jan 01 '23 11:01

Emil