November 11th 2008

Sorted Column Highlighting Widget for jQuery TableSorter Plugin Demo

Since I switched to using client side sorting for my tables via the tablesorter.js plugin created by Christian Bach, the one thing I have missed from the server side method I was using before is the highlighting of the sorted columns. It took a while to figure out how to remedy this, but I think I finally did it by creating my own widget for the plugin.

If your not familiar with the tablesorter.js plugin, you might want to check out my previous posts:

Now that you have a better idea of what the plugin can do, lets move on to today’s post where I am going to demonstrate the sorted column highlighting widget that I have created.

Live Demo | Download (HTML, CSS, JavaScript)

Screenshot of Final Product:

Sorted Column Highlighting End Product Image

jQuery for Widget:

The widget initially removes any of the sortedeven or sortedodd classes from the cells of the table that might be leftover from a previous sort. Variables containing the ascending or descending classes designated in the plugin for the header cells when the table is sorted are then set. The widget finds the header cells that have these ascending or descending classes and figures out the indexes of these columns. Finally it adds the sortedeven or sortedodd class to the cells of the column(s) as appropriate.

jQuery Functions/Methods Used:

  • removeClass -This function removes a given CSS class or the whole class attribute from the elements that match the selector(s).
  • find(expr) -Searches for all elements that match the specified expression. This method is a good way to find additional descendant elements with which to process.
  • add(expr) – Adds more elements, matched by the given expression, to the set of matched elements.
  • :nth-child(index/even/odd/equation) – Matches all elements that are the nth-child of their parent or that are the parent’s even or odd children.
  • index(subject) – Searches every matched element for the object and returns the index of the element, if found, starting with zero.
  • addClass – This function adds a CSS class to a given element.

How to Use the Widget:

Add the code for the widget to the end of the tablesorter.js file before the last line “})(jQuery);”. The download contains a modified tablesorter.js file if you have questions. Once you have added the widget, you only need to do two more things.

Make sure to call the widget when you setup the sorting for the table by adding “columnHighlight” to the list of widgets. Follow the example below:

Add sortedeven and sortedodd classes to your CSS file. As an example:

So far the widget is working with at least FF3, IE7 and Chrome with the pager plugin and multiple tables. I may of missed something though so please let me know in the comments what could be changed/improved. Be sure to checkout the live demo and the download.