Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - hiding/collapsing a <table> row [duplicate]

Tags:

jquery

css

I want table rows to disappear (by animating their height to 0px and opacity to 0). I'm using the following

$('#somecellelement').closest('tr').children('td').css('overflow','hidden');
$('#somecellelement').closest('tr').children('td').animate({
    height: '0px',
    opacity: 0
},500);

Where #somecellelement is something contained in cells of rows I want hidden. Opacity is animating correctly but the table row doesn't get smaller. If I set height: 500px then it works, but I need the row to disappear.

I cannot remove the element from DOM, though, due to scripts expecting values from form elements in those rows.

like image 311
A-OK Avatar asked Sep 27 '11 03:09

A-OK


3 Answers

If you can apply a <div> within each <td> element, then you can animate them properly. jQuery does not apply height animations to <tr> and <td>. The height animations only work on elements with display: block set, I believe.

A small change:

$('#somecellelement').closest('tr').children('td').children('div').animate(
    {height: '0px',
     opacity: 0}, 500);  

Full sample here: http://jsfiddle.net/PvwfK/

like image 167
Doozer Blake Avatar answered Nov 13 '22 07:11

Doozer Blake


As Doozer Blake's answer says, you cannot apply jQuery animations to <td> and <tr> elements. I also don't like the idea of adding a <div> element to every cell in the table in advance, because in large tables it can hurt performance.

However, you can use jQuery's wrapInner function to dynamically wrap the contents of the <td>, only when you need to animate the row:

$('#somecellelement')
    .closest('tr')
    .children('td')
    .wrapInner('<div class="td-slider" />')
    .children(".td-slider")
    .slideUp();

A word about padding

If your <td> elements have padding, they also need to be animated for a complete collapsing effect. This can be done easily with CSS3 transitions:

$('#somecellelement').closest('tr').addClass('collapsed');

And the CSS:

td {padding:10px; transition:padding 1s;}
.collapsed > td {padding:0;}
like image 30
Tzach Avatar answered Nov 13 '22 07:11

Tzach


you are animating the children, animate the <tr>

$('#somecellelement').closest('tr').animate({
    height: '0px',
    opacity: 0
},500);
like image 22
Rafay Avatar answered Nov 13 '22 08:11

Rafay