views:

377

answers:

1

How can I animate the opening/closing of table columns in jQuery?

I currently have this piece of code:

jQuery(function($){
    $(".togglebutton").click(function(e){
        if (cost_visible) {
            $(".numbers").animate({width: 80}, 1500);
            $(".costs").animate({width: 0}, 1500);

        } else {
            $(".numbers").animate({width: 0}, 1500);
            $(".costs").animate({width: 60}, 1500);
        }
    });
});

and my HTML containing standard TABLE/TR/TH/TD tags with the TH and TD tags carrying the class names used to identify what has to be opened or closed.

The problem seems to be that after jQuery touches the table, the affected cells suddenly feel the need to stack on top of eachother instead of remaining neatly in a row.

I assume this has to do with jQuery being only able to animate "block" elements, not elements that are displayed "table-like". So can I make a table out of block elements? Or is there another way to animate table-like elements? I've found this suggested solution, but it seems like a hassle to encase all your table elements into DIV's just for the animation...

+1  A: 

After some study, I've found that...

  • The problem is indeed caused by the TH and TD items being set by jQuery to "display: block" items for animation. There is as of yet no way to make jQuery behave differently.
  • Enclosing the TH and TD items in DIV tags does not work, some Google searching turns up the suggestion that HTML becomes invalid when using DIV tags within a TABLE structure.
  • Enclosing the content of TH and TD items in DIV tags does not work, the content starts to float after animation and does not stay within the TH and TD items.
  • The same article reveals that animating the opening closing of table rows is possible using TBODY sections within the table.

I succeeded in what I wanted though, and here's how:

  • I cut the table into several sub-tables consisting of the column groups I want to show and hide
  • I enclosed these sub-tables in DIV tags and floated them next to each other.
  • I used jQuery to show/hide these DIV's.

I hope that this helps anybody, and if a more elegant solution is found, please leave a message.

littlegreen
Ugh, almost a year later, and this bug has not been fixed. Thanks for the idea on how to work around it though.
daybreaker
A tricky thing about this workaround is that the table row heights can easily get out of sync. I solved that by drawing the table with visibility: none, run a jQuery loop to sync the heights to the first column and then showing the table. Good luck!
littlegreen