Phil Phil - 8 months ago 57
jQuery Question

JQuery: How to refresh event handlers

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
else {
// Open this row

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?


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);