javascriptjquerybourbon

Bourbon accordion click once expand/collapse when clicked


Hello I'm new here and I wondered if anyone could help. I have implemented bourbon.io's accordion, but I can not get it to open and collapse on a single click.

It opens, but then stays open.

$('.js-accordion-trigger').bind('click', function(e){
  jQuery(this).parent().find('.submenu').slideToggle('fast');  // apply the toggle to the ul
  jQuery(this).parent().toggleClass('is-expanded');
  e.preventDefault();
});

JSFiddle Demo


Solution

  • See below if that is what you wanted

    $('.js-accordion-trigger').on('click', function(e) {
      $('ul.submenu').not($(this).parent().find('ul.submenu')).slideUp('fast');
      $(this).parent().find('.submenu').toggleClass('is-expanded').slideToggle('fast');
      e.preventDefault();
    });
    ul.submenu {
      display: none;
    }
    
    .is-expanded {
      display: block;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul class="accordion">
      <li>
        <a href="javascript:void(0)" class="js-accordion-trigger">Accordion Item</a>
        <ul class="submenu">
          <li>
            <a href="javascript:void(0)">Sub Item 1</a>
          </li>
          <li>
            <a href="javascript:void(0)">Sub Item 2</a>
          </li>
        </ul>
      </li>
      <li>
        <a href="javascript:void(0)" class="js-accordion-trigger">Another Item</a>
        <ul class="submenu">
          <li>
            <a href="javascript:void(0)">Sub Item 1</a>
          </li>
          <li>
            <a href="javascript:void(0)">Sub Item 2</a>
          </li>
        </ul>
      </li>
    </ul>