Moving a table row with event listeners attached

I have a table implemented with Bootstrap, namely:

<table id="user-area-table" class="table">
  <thead>
     <tr>
       <th>Name</th>
       <th>Adjust</th>
       <th>Visibility</th>
       <th colspan="2">Order</th>
       <th></th>
     </tr>
  </thead>
  <tbody>
  </tbody>
</table>

and then from a select, the user populates the table. Each row in the table has a number of possible actions: up, down, delete, etc and I add event listeners to perform these actions after prepending/appending the required table row with JQuery.

On an action such as up, the existing row is removed using JQuery and I have to reinsert it into the DOM.

$("#reference").on('click', '.fa-sort-asc', function(evt) {
     $("#reference").prev().before($("#reference"));
});

The issue I have is that I now have to add event listeners as the DOM elements are all new, yet I am within one of the event listener callbacks as is. I suspect the way to deal with this is to add some code which captures any event on a tr that I have added dynamically but I am uncertain how to do that.

Update:

To add a row into the table, this is what I am currently doing. Essentially I construct the table row html using a reference and name gleaned from the select and then I insert it into the table.

var rowdata = '<tr id="' + reference + '" class="prop-layer"><td>' + name + '</td><td><a href="#"><i class="fa fa-adjust"></i></a></td><td><input type="checkbox" name="checkbox1" class="slider" data-size="mini" checked></td><td><a href="#"><i class="fa fa-sort-asc"></i></a></td><td><a href="#"><i class="fa fa-sort-desc"></i></a></td><td><a href="#"><i class="fa fa-trash"></i></a></td></tr>';
$('#user-area-table tbody').prepend(rowdata);

Answers 1

  • You assign the event handler to some parent, like body, like this:

    $("body").on('click', 'tr', function(evt) {
    });
    

    Now you can dynamically move the tr around, it will keep its event handlers. You can read more about it here: http://api.jquery.com/on/ this will point to the tr.


Related Articles