'jQuery - Open one accordion, close others

I have an accordion section and need to achieve two things:

  1. Have the first accordion open by default on page load.
  2. Everytime I click on closed accordion, open it and close the one opened previously. To always have max one accordion open.
window.PXUTheme.contentCreator.accordion = {
  init: function () {
    const $accordionHeading = $('.accordion > dt > a, [data-cc-accordion] > dt > a');
    $('.accordion > dd, [data-cc-accordion] > dd').attr('aria-hidden', true);
    $accordionHeading.attr('aria-expanded', false);
    
    const $accordionHeadingfirst = $('.accordion > dt:first-of-type > a, [data-cc-accordion] > dt > a');
    $('.accordion > dd:first-of-type, [data-cc-accordion] > dd').attr('aria-hidden', false);
    $accordionHeadingfirst.attr('aria-expanded', true);
    
    $accordionHeading.on('click', function () {
      let state = $(this).attr('aria-expanded') === 'false' ? true : false;
      $(this).attr('aria-expanded', state);
      $(this).parent().next().attr('aria-hidden', !state);
      return false;
    });
    $accordionHeading.on('keydown', function (event) {
      let keyCode = event.keyCode || e.which;

      if (keyCode === 13) {
        $(this).trigger('activate');
      }
    });
  },
  unload: function () {
    $('.accordion > dt > a, [data-cc-accordion] > dt > a').off('click activate');
    $('.accordion > dt > a, [data-cc-accordion] > dt > a').off('keydown');
  }
};

So far, I achieved 1. (although not sure it is an elegant solution), but I struggle with the second. Any advice, please?

Many thanks.



Solution 1:[1]

To always have max one accordion open.

Are you using Jquery Ui for this? Your goal is what jquery ui accordion does by default. Your code looks more complicated than it needs to be to achieve the two things you mentioned.

The following initialization code opens the first item in the container to start, and closes the opened section when a new section is opened. "#accordion" is the id of html container holding your according content.

<script>
  $( function() {
    $( "#accordion" ).accordion();
  } );
</script>

Maybe it would helpful to show us the basic html structure you are using and your Jquery script inclusions.


I don't know the full context of your project, but it might be interesting to consider if the standard html5 'details' element will a little javascript could handle your use case without the need for a 3rd party library at all.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1