jQuery slideToggle on a table with thead and tbody elements. No animation.
Asked Answered
B

2

16

I have a table with a thead and tbody sections. I have applied a slideToggle on this successfully, but the animation is broken.

When a user clicks on the thead, I want the contents of the tbody to slide up. Currently what happens is the section simply disappears, without any animation.

Here is the table

<table>
  <thead>
    <tr>
      <td colspan="3">TABLE HEADING</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="first" colspan="1">Cell Contents</td>
      <td colspan="1">Cell Contents</td>
      <td colspan="1">Cell Contents</td>
    </tr>
  </tbody>
</table>

And here is the jQuery I am using:

   <script type="text/javascript" language="javascript">
      $(document).ready(function () {
         $("thead").click(function () {
               $(this).next("tbody").slideToggle("slow");
            }
         )
      });
   </script>
Blooded answered 30/7, 2011 at 10:20 Comment(2)
These bugs happen most probably because of height settings in css.Shiver
So, perhaps I should set a height for it through jQuery when the click is triggered?Blooded
A
34

It disappears because <tbody> normally will get no shorter than the tallest td, no matter what you set its height to with CSS.

This is why the natural-height tbody just seems to disappear, while the one with artificial extra-height appears to run until the tr reached its natural height.

You can kludge around this with tbody {display:block;}. See the kludge at jsFiddle.

But, notice the effect that has when a table height is set.

Probably, the best way is to wrap the whole table in a div and slideToggle that, like so:

<table class="AbbyNormal">
    <thead><tr><td colspan="3">TABLE HEADING</td></tr></thead>
</table>
<div class="tableWrap">
    <table class="AbbyNormal">
      <tbody>
        <tr>
            <td class="first" colspan="1">Cell Contents</td>
            <td colspan="1">Cell Contents</td>
            <td colspan="1">Cell Contents</td>
        </tr>
      </tbody>
    </table>
</div>

Just be sure and fix the table widths the same.

See it in action at jsFiddle.

Atiana answered 30/7, 2011 at 13:32 Comment(2)
Thanks! That solves the problem. I ended up wrapping it in a div and using a slideToggle on the div itself.Blooded
How does this solution only have so few upvotes??? Thanks much, @Brock Adams! Ran into the same problem this morning and your solution was perfect.Ratiocinate
B
0

I think you should set an height to the tbody to make it work, look at this fiddle: http://jsfiddle.net/nicolapeluchetti/AsDvb/

css:

tbody{

    height: 1000px;
    background-color: yellow;
}
Brumbaugh answered 30/7, 2011 at 10:39 Comment(1)
I've done that, but now what seems to happen is the animation runs until the tr are at the minimum height then they just disappear.Blooded

© 2022 - 2024 — McMap. All rights reserved.