javascripthtmlonsen-uionsen-ui2

Accordion - close one item when opening another one


I want to automatically close one item when another one is open, so there is just one open at any one time.

HTML

<ons-list-item tappable class="accordion" onclick="fn.toggle(this)">List 1</ons-list-item>
  <div class="panel">
    <ons-list-item tappable>Item 1</ons-list-item>
    <ons-list-item tappable>Item 2</ons-list-item>
  </div>

JS

window.fn = {};
window.fn.toggle = function(el) {
    el.classList.toggle("active");
    el.nextElementSibling.classList.toggle("show");
}

Solution

  • This was the answer:

    window.fn = {};
    window.fn.toggle = function(el) {
      var elems = document.querySelectorAll(".accordion.active");
    [].forEach.call(elems, function(els) {
      if (el != els) {
      els.classList.toggle("active");
        els.nextElementSibling.classList.toggle("show");
      }
    });
        el.classList.toggle("active");
        el.nextElementSibling.classList.toggle("show");
    }