Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animating opening/closing of table columns in jQuery

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...

like image 466
littlegreen Avatar asked Jan 15 '10 12:01

littlegreen


2 Answers

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.

like image 123
littlegreen Avatar answered Sep 25 '22 13:09

littlegreen


While it's not the same effect, the fadeIn() and fadeOut() jQuery methods work properly on tables. The show() and hide() methods (without animation) also work.

like image 21
Rick Avatar answered Sep 25 '22 13:09

Rick