| 6 | }) |
| 7 | |
| 8 | function devToc() { |
| 9 | const expandButton = document.querySelector('.js-expand') |
| 10 | if (!expandButton) return |
| 11 | |
| 12 | const detailsElements = document.querySelectorAll('details') |
| 13 | |
| 14 | expandButton.addEventListener('click', () => { |
| 15 | // on click, toggle all the details elements open or closed |
| 16 | const anyDetailsOpen = Array.from(detailsElements).find((details) => details.open) |
| 17 | |
| 18 | for (const detailsElement of detailsElements) { |
| 19 | anyDetailsOpen ? detailsElement.removeAttribute('open') : (detailsElement.open = true) |
| 20 | } |
| 21 | |
| 22 | // toggle the button text on click |
| 23 | anyDetailsOpen |
| 24 | ? (expandButton.textContent = expandText) |
| 25 | : (expandButton.textContent = closeText) |
| 26 | }) |
| 27 | |
| 28 | // also toggle the button text on clicking any of the details elements |
| 29 | for (const detailsElement of detailsElements) { |
| 30 | detailsElement.addEventListener('click', () => { |
| 31 | expandButton.textContent = closeText |
| 32 | |
| 33 | // we can only get an accurate count of the open details elements if we wait a fraction after click |
| 34 | setTimeout(() => { |
| 35 | if (!Array.from(detailsElements).find((details) => details.open)) { |
| 36 | expandButton.textContent = expandText |
| 37 | } |
| 38 | }, 50) |
| 39 | }) |
| 40 | } |
| 41 | } |