0

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");
}
Antonio Andrés
  • 169
  • 2
  • 15
  • I'm unsure if it is a requirement to only use JavaScript, if it's not, have a look at [jQuery UI - Accordion](https://jqueryui.com/accordion/) – Roy Scheffers Aug 07 '18 at 20:41
  • The quick and dirty way would be to onClick close ALL panels, then open just the panel that was clicked. Won't affect already closed panels. – TJBlackman Aug 07 '18 at 20:44
  • Here is a quick example I found on the interwebs, take a look and see if you can find your answer in there. https://codepen.io/sureshrkm/pen/ZbzBpr – Adam H Aug 07 '18 at 20:50

1 Answers1

0

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");
}
Antonio Andrés
  • 169
  • 2
  • 15