|
30 | 30 | // Default settings for the Nav class |
31 | 31 | static defaultSettings = { |
32 | 32 | menuHoverClass: 'show-menu', |
33 | | - dir: 'ltr' |
| 33 | + dir: 'ltr', |
| 34 | + preventSubmenuOpenOnload: 'nav-active-open' |
34 | 35 | }; |
35 | 36 |
|
36 | 37 | constructor(nav, settings = {}) { |
|
79 | 80 |
|
80 | 81 | nav.addEventListener('keydown', this.onMenuKeyDown.bind(this)); |
81 | 82 | nav.addEventListener('click', this.onClick.bind(this)); |
| 83 | + |
| 84 | + if (this.nav.classList.contains(this.settings.preventSubmenuOpenOnload)) { |
| 85 | + this.toggleAllForCurrentActive(); |
| 86 | + } |
82 | 87 | } |
83 | 88 |
|
84 | 89 | onMenuKeyDown(event) { |
|
203 | 208 | ulChild.setAttribute('aria-hidden', open ? 'false' : 'true'); |
204 | 209 | ulChild.classList.toggle(this.settings.menuHoverClass, open); |
205 | 210 | }); |
206 | | - target.querySelector(':scope > [aria-expanded]').setAttribute('aria-expanded', open ? 'true' : 'false'); |
| 211 | + target.querySelector(':scope > [aria-expanded]')?.setAttribute('aria-expanded', open ? 'true' : 'false'); |
207 | 212 | } |
208 | 213 |
|
209 | 214 | focusTabbable(direction = 1) { |
|
232 | 237 | } |
233 | 238 | return currentLi; // top-level li or null if not found, or the |
234 | 239 | } |
| 240 | + |
| 241 | + toggleAllForCurrentActive() { |
| 242 | + const active = this.nav.querySelector('.current.active'); |
| 243 | + if (active) { |
| 244 | + const $parentTopLevel = this.getTopLevelParentLi(active); |
| 245 | + let currentLi = active; |
| 246 | + while (currentLi && !Array.from(this.topLevelNodes).includes(currentLi)) { |
| 247 | + const parentUl = currentLi.parentElement.closest('ul'); |
| 248 | + currentLi = parentUl ? parentUl.closest('li') : null; |
| 249 | + if (currentLi) { |
| 250 | + const subLists = currentLi.querySelectorAll('ul'); |
| 251 | + this.toggleSubMenu(currentLi, subLists, subLists[0]?.getAttribute('aria-hidden') === 'true'); |
| 252 | + } |
| 253 | + } |
| 254 | + } |
| 255 | + } |
235 | 256 | } |
236 | 257 |
|
237 | 258 | // static idCounter for unique id generation of submenus |
|
0 commit comments