Toggle Table Rows with jQuery, no plug-in required

Last week I encountered a situation with one of our web apps that required a toggle-able table row. Essentially the existing table was populated with information from four different tables. In addition to several joins there were some nested queries, and it was killing the MySQL server.

So, I decided to pull the information from the nested queries out of the rows and use a hidden table row below each existing row where I would show the formerly nested information using an ajax call to retrieve. Removing the nested queries significantly improved query performance.

The biggest problem in this was creating a table row that toggles. The native toggle() jquery function didn’t work at first, and this is because a table row’s display attribute is “table-row”, and not “block” as toggle() resets to.

I found this jQuery plugin by Janko at Warp Speed for doing exactly what I need. It is simple and works quite well with the minimum necessary amount of code. This is accomplished by using jQuery calls to add an anonymous click function to the even rows. However, there are some drawbacks. First, if you observe the demo, notice that a click anywhere in the parent row triggers the toggle.  This is great unless you have a link in the parent row.  What to do if you have, say, a table of employees and you want a link to their full record in the parent row?

Quite unintentionally, after fiddling with jQuery for a couple of hours I came up with a solution.  Only after I tested did I realize I had Janko’s plugin commented out.  I was able to confirm my solution works with no plugin required.  Rather than using the odd/even selectors in jQuery, I have used row ID numbers as you will see in the demo.  To exempt the cell with the link from the anonymous click function, I have added the clickable class to each cell instead.  If you don’t want this extra layer of complexity, just strip out all the parent() business from the JavaScript.

Please help yourself to the code and let me know what you think. View the demo…

P.S. In case you are wondering why I have an empty third row for each record:  This is to preserve the jQuery-based alternating table row highlighting that uses the jQuery even selector.  Since Janko’s solution also relies on this method, it was wiping out my table striping.