2

I am in the process of updating my site to jQuery 1.7 with plans to update to the latest version as a phase 2. Below is my existing livequery code that I need to update to .on() in order to maintain the table sorting functionality.

// EXISTING CODE - Applies table sorting to existing and future tables with class of tablesorter
$("table.tablesorter").livequery(function(){ // need to replace this .livequery code

I can use this code to enable table sorting on tables that exist when DOM has loaded, but it will not work on tables created after DOM is loaded.

// Only works on existing tables
$('table.tablesorter').tablesorter();

I tried the following code with .on but it does not respond to the first click

// Works on existing tables and tables created later, but it will not respond to initial click event
$(document).on('click', 'table.tablesorter', function(e){  $('table.tablesorter').tablesorter(); });

Any recommendations will be greatly appreciated.

12AX7
  • 310
  • 4
  • 14
  • Unfortunately `.on` does not have that functionality by design. The simplest way would be to just keep livequery; it does it in pretty much the most efficient way short of running said code directly after making the dom changes(recommended, but may require logic changes) – Kevin B Mar 18 '13 at 17:36
  • 1
    If you are going to depart from livequery, then use either [Mottie's fork of tablesorter](https://github.com/Mottie/tablesorter), which fixes all sorts of issues in Christian Bach's original, or [dataTables](http://www.datatables.net/). With both of these plugins, you need to invoke them explicitly on freshly made tables - eg. `$(myNewTable).tablesorter();`. The duty of ".live()" is to delegate event handling; it cannot establish an automatic "widgetization" rule. – Beetroot-Beetroot Mar 18 '13 at 17:56
  • Thx for the replies. I can't keep using livequery after upgrading to jQuery 1.7. However, regarding the Christian Bach updated tablesorter vs. DataTables, can you recommend one over the other? – 12AX7 Mar 18 '13 at 20:12
  • If you are controlling the page updates (e.g. ajax loading), then the best solution would be to initialize the table after it has completed (like in an ajax callback function). – Mottie Mar 19 '13 at 17:51
  • 1
    Mottie - Can you please give me an example of "initialize the table after it has completed (like in an ajax callback function)"? – 12AX7 Mar 19 '13 at 19:21

1 Answers1

0

If you are using ajax to load in the table data, just initialize the table in the callback function (or done function as shown below; demo):

$.ajax({
  type: "GET",
  // should return raw html of the table
  url: "mysite.com/table"
}).done(function(data) {
  // add the table
  $(data).appendTo('body');
  // initialize it
  $('table').tablesorter({
    theme : 'blue'
  });
});

This is just one of many examples.

Mottie
  • 84,355
  • 30
  • 126
  • 241