Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rebind jquery events to content loaded via ajax WITHOUT doing this for every event / class

So I have this jquery-App where I bind:

  • a "delete-function" to all my ".btn-delete" elements
  • a "add-function" to all my ".btn-add" elements

and so on. Within one div of my webapp I do asynchronous loading of content, including elements that I want to bind the "delete" and "add" functions to. These elements also have a "btn-delete" or "btn-add" class - but since the content is loaded asynchronously the events are not bound to them without doing something about it.

So I heard that with the .on('click' ...) function which can be triggered right after loading the content asynchronously, I can rebind these functions. But I would have to do that for every function that I want to use. That I do not want.

What I would like is to have a generic function that rebinds ALL previously defined event-functions to every element within the div-container I loaded them into.

Is there a way to do something like:

"rebind all event-functions to asynchronously loaded elements within div-id xyz"

It would make my life so much easier if I didn't have to rebind every function with every callback manually.

like image 716
michl_sof Avatar asked Oct 25 '13 15:10

michl_sof


1 Answers

If you use delegated event handling, you never have to re-bind.

$('body').on('click', '.btn-delete', function(ev) {
  // delete ...
});

That sets up an event handler that catches "click" events when they bubble up to the body from any element, at any time. It acts on any "click" from an element that matches the given selector. Whether the button was there originally or added dynamically doesn't matter.

You don't have to put the handlers on the <body> element; they can go at any layer of container.

like image 78
Pointy Avatar answered Nov 03 '22 18:11

Pointy