| 1 | (function () |
| 2 | { |
| 3 | const btn = document.getElementById('chapterMenuBtn'); |
| 4 | const dropdown = document.getElementById('chapterDropdown'); |
| 5 | |
| 6 | if (btn && dropdown) |
| 7 | { |
| 8 | function closeDropdown () |
| 9 | { |
| 10 | dropdown.classList.remove('open'); |
| 11 | btn.setAttribute('aria-expanded', 'false'); |
| 12 | } |
| 13 | |
| 14 | btn.addEventListener('click', () => |
| 15 | { |
| 16 | const isOpen = dropdown.classList.toggle('open'); |
| 17 | btn.setAttribute('aria-expanded', isOpen ? 'true' : 'false'); |
| 18 | }); |
| 19 | |
| 20 | // Click outside closes it |
| 21 | document.addEventListener('click', (e) => |
| 22 | { |
| 23 | if (!e.target.closest('.chapterPicker')) closeDropdown(); |
| 24 | }); |
| 25 | |
| 26 | // Smooth scroll when selecting a chapter |
| 27 | dropdown.addEventListener('click', (e) => |
| 28 | { |
| 29 | const target = e.target.closest('button[data-target]'); |
| 30 | if (!target) return; |
| 31 | |
| 32 | const id = target.getAttribute('data-target'); |
| 33 | const el = document.getElementById(id); |
| 34 | if (el) |
| 35 | { |
| 36 | el.scrollIntoView({ behavior: 'smooth', block: 'start' }); |
| 37 | closeDropdown(); |
| 38 | history.replaceState(null, '', '#' + id); // optional: update URL fragment |
| 39 | } |
| 40 | }); |
| 41 | } |
| 42 | |
| 43 | const scrollLinks = document.getElementsByClassName('scrollLink'); |
| 44 | for (let i = 0; i < scrollLinks.length; i++) |
| 45 | { |
| 46 | scrollLinks[i].addEventListener('click', (e) => |
| 47 | { |
| 48 | const target = e.target.closest('a[data-target]'); |
| 49 | console.log("Scrolling to " + target); |
| 50 | if (!target) return; |
| 51 | |
| 52 | const id = target.getAttribute('data-target'); |
| 53 | const el = document.getElementById(id); |
| 54 | if (el) |
| 55 | { |
| 56 | el.scrollIntoView({ behavior: 'smooth', block: 'start' }); |
| 57 | closeDropdown(); |
| 58 | history.replaceState(null, '', '#' + id); // optional: update URL fragment |
| 59 | } |
| 60 | }); |
| 61 | } |
| 62 | })(); |