Web Component (LIT) - Accordion close on open of other

93 views Asked by At

I am using the and trying to close the open accordion when another accordion is selected. But unable to do so. Any help is highly appreciated.

<lion-accordion>
  <h3 slot="invoker">
    <button>Sensory Factors</button>
  </h3>
  <div slot="content" class="lion-paragraph-container">
    <p>
     Content A
    </p>
    
  </div>
  <h3 slot="invoker">
    <button>Nutritional value</button>
  </h3>
  <div slot="content">
    Content B
  </div>
</lion-accordion>
1

There are 1 answers

1
Danny '365CSI' Engelman On

If you have a hammer, everything starts to lit like a nail

Why create dependencies on Lit and Lion?

It is almost a one-liner <details-accordion> native Web Component
wrapping native HTML <details> <summary> code

Throwing in ctrl-click for free

<style>
  summary { font-weight: bold; cursor: pointer }
  details[open] { background: beige  }
</style>

<details-accordion>
  <details open>
    <summary>Summary 1</summary>
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
  </details>
  <details>
    <summary>Summary 2</summary>
      "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
  </details>
  <details>
    <summary>Summary 3</summary>
      "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
   </details>
</details-accordion>

<script>
customElements.define(
  'details-accordion', class extends HTMLElement {
    connectedCallback() {
      this.onclick = e => [...this.children].forEach(d => 
                                    !e.ctrlKey 
                                      && 
                                    d.toggleAttribute("open", e.target == d));
    }
  });
</script>

Do read: