htmlhtml-tag-details

How to close details tag when other is open or a click is made outside the tag


this code below almost does the trick. If you open any details tag and then click anywhere outside of it it will close. However, currently open details tags wont close as a new details tag is open.

var details = [...document.querySelectorAll('details')];
document.addEventListener('click', function(e) {
  if (!details.some(f => f.contains(e.target))) {
    details.forEach(f => f.removeAttribute('open'));
  }
})
<details>
  <summary>Details 1</summary>
  <p>content</p>
</details>

<details>
  <summary>Details 2</summary>
  <p>content</p>
</details>

<details>
  <summary>Details 3</summary>
  <p>content</p>
</details>

What am I missing?


Solution

  • You can check whether the target is a details tag, and if not, close all details tags.

    If it is, only close the ones that don't have the event target as a child.

    var details = [...document.querySelectorAll('details')];
    document.addEventListener('click', function(e) {
      if (!details.some(f => f.contains(e.target))) {
        details.forEach(f => f.removeAttribute('open'));
      } else {
        details.forEach(f => !f.contains(e.target) ? f.removeAttribute('open') : '');
      }
    })
    <details>
      <summary>Details 1</summary>
      <p>content</p>
    </details>
    
    <details>
      <summary>Details 2</summary>
      <p>content</p>
    </details>
    
    <details>
      <summary>Details 3</summary>
      <p>content</p>
    </details>