forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
41 lines (33 loc) · 1.3 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const expandText = 'Expand All'
const closeText = 'Close All'
document.addEventListener('DOMContentLoaded', async () => {
devToc()
})
function devToc() {
const expandButton = document.querySelector('.js-expand')
if (!expandButton) return
const detailsElements = document.querySelectorAll('details')
expandButton.addEventListener('click', () => {
// on click, toggle all the details elements open or closed
const anyDetailsOpen = Array.from(detailsElements).find((details) => details.open)
for (const detailsElement of detailsElements) {
anyDetailsOpen ? detailsElement.removeAttribute('open') : (detailsElement.open = true)
}
// toggle the button text on click
anyDetailsOpen
? (expandButton.textContent = expandText)
: (expandButton.textContent = closeText)
})
// also toggle the button text on clicking any of the details elements
for (const detailsElement of detailsElements) {
detailsElement.addEventListener('click', () => {
expandButton.textContent = closeText
// we can only get an accurate count of the open details elements if we wait a fraction after click
setTimeout(() => {
if (!Array.from(detailsElements).find((details) => details.open)) {
expandButton.textContent = expandText
}
}, 50)
})
}
}