Search code examples
javascriptjquerytoggleforummybb

Single slideToggle() for the same elements


I have this code HTML:

<div>
    <div>
        <button class="btn-slide"><span class="fa fa-caret-down" aria-hidden="true"></span></button>
    </div>
    <div class="block">
    ...
    </div>
</div>

And I have several such elements in my forum template. I use standard js toggle() script:

$(document).ready(function() {
    $('btn-slide').click(function() {
        $('.block').slideToggle(50);
    });
});

And when I click on button all components show or hide but I want to hide/show only this element which I choose. I thought that I can use $(this).childern in 3rd line but if you see .block isn't a btn-slide childern. So how can I achieve what I want?


Solution

  • You can use parents() next()

    $(document).ready(function() {
      $('.btn-slide').click(function() {
        $(this)
          // get all div in parent level
          .parents('div')
          // get immediate sibling with class block after the element 
          .next('.block')
          .slideToggle(50);
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div>
      <div>
        <button class="btn-slide"><span class="fa fa-caret-down" aria-hidden="true"></span>
        </button>
      </div>
      <div class="block">
        ...
      </div>
    </div>
    
    <div>
      <div>
        <div>
          <div>
            <button class="btn-slide">
              <span class="fa fa-caret-down" aria-hidden="true"></span>
            </button>
          </div>
        </div>
      </div>
      <div class="block">
        ...
      </div>
    </div>