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.
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.
Share Improve this question edited Feb 21, 2014 at 11:28 BenMorel 36.6k51 gold badges205 silver badges335 bronze badges asked Oct 25, 2013 at 15:10 michl_sofmichl_sof 1011 silver badge6 bronze badges1 Answer
Reset to default 16If 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.