1

I'm trying to expand/collapse a row using jQuery (although I don't really care how I accomplish it, but I feel like I'm very close).

So here is my table:

$(document).ready(
  function() {
    $(".toggler").click(
      function() {
        if ($(this).hasClass('expanded')) {
          $(this).animate({
            height: 20
          }, 200).removeClass('expanded');
          //I KNOW THIS ISN'T RIGHT
          $(this).parents().siblings().animate({
            height: 20
          }, 200);
        } else {
          $(this).animate({
            height: 100
          }, 200).addClass('expanded');
          //I KNOW THIS ISN'T RIGHT
          $(this).parents().siblings().animate({
            height: 100
          }, 200);
        }
      }
    );
  }
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td width=10px;>
      <a href="#" class="toggler">
        <div class="toggler" style="height:20px; overflow:hidden">+</div>
      </a>
    </td>
    <td class="toggler" width=100px;>
      <div class="toggler" style="height:20px; overflow:hidden">Apples and other information here</div>
    </td>
    <td class="toggler">
      <div class="toggler" style="height:20px; overflow:hidden">100</div>
    </td>
    <td>
      <div style="height:20px;">22/10</div>
    </td>
  </tr>
  <tr>
    <td width=10px;>
      <a href="#" class="toggler">
        <div class="toggler" style="height:20px; overflow:hidden">+</div>
      </a>
    </td>
    <td class="toggler" width=100px;>
      <div class="toggler" style="height:20px; overflow:hidden">Peaches plus more text in here that will span multiple rows.</div>
    </td>
    <td class="toggler" width=50px;>
      <div class="toggler" style="height:20px; overflow:hidden">100 and then some more stuff.</div>
    </td>
    <td>
      <div style="height:20px;">22/10</div>
    </td>
  </tr>
</table>

I've tried different versions of:

$(this).parents.siblings().animate({height:100},200);

and I realize I could rename the 2nd row in my table to something like toggle2 and just have a different function and then hard code the names, but I want this to work when this is expanded to hundreds of rows and don't really want to write 100's of functions for this.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • Does this answer your question? [expand/collapse table rows with JQuery](https://stackoverflow.com/questions/16926752/expand-collapse-table-rows-with-jquery) – kmoser Oct 06 '22 at 03:20

0 Answers0