Crystallize Crystallize - 4 months ago 12
HTML Question

Binding Jquery event to a button in an Async event response

I have a page that sends an asyncronous Jquery request to another page, and i receive a button in response.
Button has class "delete_button".

<BUTTON class="delete_button">Delete</BUTTON>


The problem is, this "new" button is not bound (and doesn't trigger) any Jquery event.

I've tried to use the .on() function (And the old deprecated .live()) but i couldn't bind an event to that button. The Jquery even is as follows.

$(".delete_button").on("click", function(){
//Code here...
});


I've checked using a debugger that the button actually has the correct class, and the Javascript signals no error. Nothing strange in the console.
Simply, the event does not occur.

Answer

Let's say when you receive your delete_button that it gets appended to a div, so that it's within that div, e.g.

<div id="myDiv">
  <button class="delete_button">Delete</button>
</div>

Knowing this, you can create an on event like this:

$("#myDiv").on("click", ".delete_button", function(){
  //Code here...
}); 

That way the event is bound to an element which definitely exists, and then jQuery delegates that event to any dynamically created elements with the .delete_button selector.

The way you're doing it currently, it doesn't matter that you use .on, because the initial selector (in the $("selector")) part has to be something that exists when the page loads. See http://api.jquery.com/on/ and the section called "Direct and delegated events" for a fuller explanation.