Reputation: 2236
I have a Jquery handler bound to a DOM element.
$('.details-control').click( function () {
var tr = $(this).closest('tr.parentRow');
var row = table.row(tr);
var nestedTable = tr.children('td.nested').children('table.nested').clone(true);
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child(nestedTable).show();
tr.addClass('shown');
}
});
The above element is in a paginated table, so when the table gets paginated the ('.details-control') elements on the page change and these do not have the event attached.
I would like to have the events attached to these new $('details-control') elements.
The only way I can think of is to rewrite the code again like below...
$('.pagination').click( function () {
//copy-paste $('.details-control').click( function () {....
});
But I think there must be a better way.. but nothing comes up in my searches because I'm not sure what search terms this even falls under.
Is there a way I can name the details-control event and call it or so I don't have to copy-paste or a way to reattach or refresh the handlers?
Upvotes: 0
Views: 1434
Reputation: 43718
You are looking for event delegation which is the process of attaching the handler on a container and filtering events that bubble-up according to a specific criteria (a selector in this case). Assuming .pagination
is the parent of .details-control
and that parent never gets replaced:
$('.pagination').on('click', '.details-control', yourHandler);
Upvotes: 2
Reputation: 2146
Use on handlers.
$(document).ready(function() {
$( selector ).on('click', function () {
// logic
})
})
You can turn these on and off dynamically with on() and off()
Upvotes: 0