Accordion - close one item when opening another one

1.5k Views Asked by At

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");
}
1

There are 1 best solutions below

0
On BEST ANSWER

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");
}