Table animations in jQuery.

Wednesday, August 5, 2009 12:56
Posted in category Web

If you ever tried to do some animation of tables or table rows with jQuery you will have found that this is not an easy task. The primary reason of animation ‘not working’ in jQuery for these kind of objects is that these elements are not block-level elements.

In CSS that means that these elements are displayed with “display:table-row”. Animations in jQuery only work with elements that are displayed with “display:block” or equivalents.

Simply changing the display style of a table row or table to ‘block’ will break your table ‘design’.

Hence, some other method has to be found to create ‘table animations’ in jQuery.

I have come up with one solution. It’s not very nice, and it might require a ‘fast’ computer, but at least it works.

Here is an example of my code that hides/shows the <tbody> element of a table. (So it will do nothing with the <thead> and <tfoot> rows.) The code can easily be modified to ‘animate’ an entire table or just a single row;

 1: function hideTableBody(tableid)
 2: {
 3: $(tableid).children("tbody").children("tr").children("td").wrapInner("<div />").children("div").slideUp(500, function () {$(this).parent().parent().hide();});
 4: }
 5: function showTableBody(tableid)
 6: {
 7: $(tableid).children("tbody").children("tr").show().children("td").children("div").slideDown(500,function () {$(this).replaceWith($(this).contents());});
 8: }

 

What hideTableBody essentially does is find all <tbody> elements of a table, then find all rows in that element, then find all cells in each row and wrap all contents of the cells in a <div>. It then uses ‘slideUp’ to animate that div. After it’s done, it hides the table row. (To be honest, the last cells of the table might not already be done animating when they are hidden, but I don’t think anyone will notice.)

After the hideTableBody is done, you might see the table get smaller because there is no more content to display. If that is the case, please set the proper width to all header cells.

showTableBody does exactly the reverse.

You can speed up things by placing all cell content in a <div> to start with. You can then get rid of the ‘wrapInner’ and ‘replaceWith’ commands in the code.

Have fun!

You can leave a response, or trackback from your own site.

Leave a Reply

You must be logged in to post a comment.