Oliver Kucharzewski
Oliver Kucharzewski

Reputation: 2645

Setting accordion to active based on active child

The top accordion section is 'active'. I want to achieve a menu that becomes active based on the child elements. For example; as you can see 'Dashboard' is set to active with an 'active' class because it is the current page.

How can I make an accordion active if a child element has the class 'active'? (like a dropdown menu on a website)

Navigation Accordion

Code:

<nav id="side-nav">
    <div class="accordion ui-accordion ui-widget ui-helper-reset" role="tablist">
        <h3 class="ui-accordion-header ui-helper-reset ui-state-default ui-accordion-header-active ui-state-active ui-corner-top ui-accordion-icons" role="tab" id="ui-accordion-1-header-0" aria-controls="ui-accordion-1-panel-0" aria-selected="true" tabindex="0">
            <span class="ui-accordion-header-icon ui-icon ui-icon-triangle-1-s"></span>Core Application
        </h3>
        <div class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active" id="ui-accordion-1-panel-0" aria-labelledby="ui-accordion-1-header-0" role="tabpanel" aria-expanded="true" aria-hidden="false" style="display: block; height: 360px;">
            <a class="active" href="">Dashboard</a>
            <a href="customers">Customers</a>
            <a href="staff">Staff</a>
            <a href="tours">Tours</a>
            <a href="users">Users</a>
            <a href="settings">Settings</a>
        </div>
        <h3 class="ui-accordion-header ui-helper-reset ui-state-default ui-corner-all ui-accordion-icons" role="tab" id="ui-accordion-1-header-1" aria-controls="ui-accordion-1-panel-1" aria-selected="false" tabindex="-1">
            <span class="ui-accordion-header-icon ui-icon ui-icon-triangle-1-e"></span>Another menu
        </h3>
        <div class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" id="ui-accordion-1-panel-1" aria-labelledby="ui-accordion-1-header-1" role="tabpanel" aria-expanded="false" aria-hidden="true" style="display: none; height: 360px;">
            <a href="medication/records"><b class=""></b>Medical Records</a>
        </div>
    </div>
    <script> $(".accordion").accordion();</script>
</nav>

Upvotes: 0

Views: 3822

Answers (1)

Twisty
Twisty

Reputation: 30883

You are looking to set the active option for Accordian. See more: http://api.jqueryui.com/accordion/#option-active

This can be done like so:

<script>
$(function() {
  var activeTab = 0;
  $(".accordion div").each(function(i, el) {
    if ($(el).find(".active").length) {
      activeTab = i;
    }
  });
  $(".accordion").accordion({
    active: activeTab
  });
});
</script>

The Panel that has a link that has active as a class will then be open when the page loads.

Working example: https://jsfiddle.net/Twisty/76jrtx62/

Upvotes: 2

Related Questions