Search code examples
jqueryaccordionslidetogglenextuntil

jQuery accordion using nextUntil


I have created an accordion using the nextUntil() function. When an accordion item is clicked, I would like to close the previously active item.

HTML:

<div class="accordion">
  <h3>Item 1</h3>
  <p>...</p>
  <p>...</p>
  <h3>Item 2</h3>
  <p>...</p>
  <p>...</p>
  <h3>Item 3</h3>
  <p>...</p>
  <p>...</p>
</div>

jQuery:

$(document).ready(function() {
  $('.accordion p').hide();
  $('.accordion h3').click(function(e) {
    e.preventDefault();
  
    var $this = $(this);
    $this.nextUntil('.accordion h3').slideToggle('fast');
  });
});

I need the DOM exactly as shown above and cannot have the nested <p> elements.

Here is a demo of what I have done so far: https://jsfiddle.net/L6q4pako/

I wasn't able to correctly use the siblings() function to hide the previously active <p> tags.


Solution

  • If you just want to hide all the other <p> tags, you can use the :not() Selector like this: $('.accordion p:not(this)').hide('fast');

    $(document).ready(function() {
        $('.accordion p').hide();
        $('.accordion h3').click(function(e) {
            e.preventDefault();
          
            var $this = $(this);
          $('.accordion p:not(this)').hide('fast');
            $this.nextUntil('.accordion h3').slideToggle('fast');
        });
    });
    h3 { cursor:pointer; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="accordion">
    <h3>
    Item 1
    </h3>
    <p>
    sdfs dsf sdf sdf sdf sd
    </p>
    <p>
    sdfsdfsd sdf sdf sdf sdf sdf sdf sdf sdf asdfasd fasdf asdf asdf.
    </p>
    <h3>
    Item 2
    </h3>
    <p>
    e449935934b3453495439
    </p>
    <p>
    sdfijdfjjsl slsdlsls ls
    </p>
    <h3>
    Item 3
    </h3>
    <p>
    fsds ss sdfs
    </p>
    <p>
    345345334 sdfsdfsd
    </p>
    </div>