Skip to content

Commit e6629a6

Browse files
committed
fix Expand and Close toggling
1 parent 739396f commit e6629a6

1 file changed

Lines changed: 23 additions & 7 deletions

File tree

javascripts/dev-toc.js

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,35 @@ export default function devToc () {
55
const expandButton = document.querySelector('.js-expand')
66
if (!expandButton) return
77

8-
expandButton.addEventListener('click', () => {
9-
// on click, toggle the button text
10-
expandButton.textContent === expandText
11-
? expandButton.textContent = closeText
12-
: expandButton.textContent = expandText
8+
const detailsElements = document.querySelectorAll('details')
139

10+
expandButton.addEventListener('click', () => {
1411
// on click, toggle all the details elements open or closed
15-
const detailsElements = document.querySelectorAll('details')
12+
const anyDetailsOpen = Array.from(detailsElements).find(details => details.open)
1613

1714
for (const detailsElement of detailsElements) {
18-
detailsElement.open
15+
anyDetailsOpen
1916
? detailsElement.removeAttribute('open')
2017
: detailsElement.open = true
2118
}
19+
20+
// toggle the button text on click
21+
anyDetailsOpen
22+
? expandButton.textContent = expandText
23+
: expandButton.textContent = closeText
2224
})
25+
26+
// also toggle the button text on clicking any of the details elements
27+
for (const detailsElement of detailsElements) {
28+
detailsElement.addEventListener('click', () => {
29+
expandButton.textContent = closeText
30+
31+
// we can only get an accurate count of the open details elements if we wait a fraction after click
32+
setTimeout(() => {
33+
if (!Array.from(detailsElements).find(details => details.open)) {
34+
expandButton.textContent = expandText
35+
}
36+
}, 50)
37+
})
38+
}
2339
}

0 commit comments

Comments
 (0)