Ralf
Ralf

Reputation: 75

Close all jQuery Accordions on open

I am using multiple sepearate accordions on a page at different places. If i open one accordion tab, all the other "independant" accordions should close.

As you can see here: jsfiddle

example at jsfiddle

If i open "SECOND Accordion - Secion x", all sections from "First Accordion" should collapse. I need universal code, so ALL OTHER should close.

Thanks in advance!

Upvotes: 0

Views: 73

Answers (2)

Paul T.
Paul T.

Reputation: 4907

Try the runnable example below.

I've added a 3rd accordion to see the behavior. Only one of the 3 accordions will be active, the others will collapse.

$( function() {
    $( ".accordion" ).accordion({
      heightStyle: "content",
      collapsible: true,
      active: false
    });

    $('.accordion').click(function() {
      // Get all the accordions
      let accordions = $('.accordion');

      // Remove the clicked accordion
      accordions.splice($('.accordion').index($(this)), 1);
      
      // Deactivate the other accordions
      $(accordions).accordion('option', 'active', false);
    });
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div class="accordion">
    <h3>First Accordion - Section 1</h3>
    <div>
        <p>Mauris mauris ante, blandit et, ultrices a.</p>
    </div>
    <h3>First Accordion - Section 2</h3>
    <div>
        <p>Mauris mauris ante, blandit et, ultrices a.</p>
    </div>
</div>

<hr>
Some other content
<hr>

<div class="accordion">
    <h3>SECOND Accordion - Section 1</h3>
    <div>
        <p>Mauris mauris ante, blandit et, ultrices a.</p>
    </div>
    <h3>SECOND Accordion - Section 2</h3>
    <div>
        <p>Mauris mauris ante, blandit et, ultrices a.</p>
    </div>
</div>

<hr>
Even MORE content
<hr>

<div class="accordion">
    <h3>3rd Accordion - Section 1</h3>
    <div>
        <p>Mauris mauris ante, blandit et, ultrices a.</p>
    </div>
    <h3>3rd Accordion - Section 2</h3>
    <div>
        <p>Mauris mauris ante, blandit et, ultrices a.</p>
    </div>
</div>

Upvotes: 1

Ved Singhal
Ved Singhal

Reputation: 86

Below code snippet help you to achieve what you want

$(function() {
  $(".accordion").accordion({
    heightStyle: "content",
    collapsible: true,
    active: false,
    beforeActivate: function( event, ui ) { 
        $(".ui-accordion-content").slideUp(1000);
    }
  });
});

Upvotes: 0

Related Questions