0

I'm looking for a little jquery help to collapse/expand a table that I have on my site. I'd also like the table to start expanded.

Here is an example of a table I have:

<table class="table">
  <caption>
  <div class="video-header">Header</div>
  </caption>
  <tbody>
    <tr class="video-row">
      <td class="field-title"> Content </td>
    </tr>
    <tr class="video-row">
      <td class="field-title"> More Content</td>
    </tr>
  </tbody>
</table>

I'd like it that when you click on the "Header" that it collapses the entire table, not just the row.

I've found the following example, but can't seem to translate it to my case.

Dan
  • 1,709
  • 5
  • 15
  • 21

2 Answers2

0

Just write a click handler for the caption element

jQuery(function () {
    $('table > caption').click(function () {
        $(this).next().toggle();
    })
})

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Arun, would it be possible to have a "+/-" symbol to show when it is collapsed or expanded? – Dan Jan 07 '14 at 02:36
  • Thanks Arun! One more question, is there anyway to make the collapse and expand have a sliding transition rather then just showing and disappearing? – Dan Jan 07 '14 at 03:12
  • @Dan it looks a little difficult with current markup http://stackoverflow.com/questions/6882522/jquery-slidetoggle-on-a-table-with-thead-and-tbody-elements-no-animation – Arun P Johny Jan 07 '14 at 03:18
0

because your table is generated dynamically, you should define a parent node in which the table is located. this parent node should always exist in the page and should NOT be generated dynamically.

  <div id="table-container">
    <table class="table">
      <caption>
      <div class="video-header">Header</div>
      </caption>
      <tbody>
        <tr class="video-row">
          <td class="field-title"> Content </td>
        </tr>
        <tr class="video-row">
          <td class="field-title"> More Content</td>
        </tr>
      </tbody>
    </table>
  </div>

then bind click event on that parent node.

$("#table-container caption").on("click", function(){
  $("#table-container table").css("display", "none");
});
Freedom
  • 803
  • 10
  • 26