Tutorials
jQueryWhen large sets of data are grouped in tables, as each year's set of articles are in our News page, collapsing, or hiding, a section's contents can be a convenient way to get a broad view of all of the table's data without having to scroll so much.
To make the sections of the news article table collapsible, we first prepend a minus-symbol image to each subheading row's first cell. The image is inserted with JavaScript, because if JavaScript is not available for the row collapsing, the image might confuse those who expect clicking on it to actually trigger some kind of event:
Note that we set variables for the location of both a minus-symbol and a plus-symbol image. This way we can change the image's src attribute when the image is clicked and the rows are collapsed or expanded.
Next we use the .addClass() method to make the newly created images appear clickable:
Finally, we can add code inside a .click() method to do the collapsing and expanding. A condition will check the current value of the clicked image's src attribute. If it equals the file path represented by the toggleMinus variable, then all of the other <tr> elements within the same <tbody> will be hidden, and the src attribute will be set to the value of the togglePlus variable. Otherwise, these <tr> elements will be shown and the src will change back to the value of toggleMinus:
With this code in place, clicking on the minus-symbol image next to 2007 makes the table look like this:

The 2007 news articles aren't removed; they are just hidden until we click the plus-symbol image that now appears in that row.
Table rows present particular obstacles to animation, since browsers use different values (table-row and block) for their visible display property. The .hide() and .show() methods, without animation, are always safe to use with table rows. As of jQuery version 1.1.3, .fadeIn() and .fadeOut() can be used as well.
| Great post! Do you have a method for indicating the item count for each group? So, if the group is collapsed, you know how many items it has. |
| I have implemented this, but MSIE has a problem that does not happen in Safari, Chrome, or Firefox. my tbody sections initialize open just fine, and in MSIE, a click on the icon switches the icon and fades the tbody out. But the next click on the icon does nothing, in never will fadeIn again in MSIE. Do you know of a workaround? |