| 1 | behavior Scrollspy |
| 2 | |
| 3 | def activate(hash) |
| 4 | for a in <a[aria-current]/> in me |
| 5 | remove @aria-current from a |
| 6 | end |
| 7 | set link to first <a[href='${hash}']/> in me |
| 8 | if link exists |
| 9 | set link's @aria-current to 'true' |
| 10 | set pageY to window.scrollY |
| 11 | call link.scrollIntoView({block: 'nearest', behavior: 'instant'}) |
| 12 | call window.scrollTo(0, pageY) |
| 13 | end |
| 14 | end |
| 15 | |
| 16 | on scroll from window throttled at 50ms |
| 17 | set current to null |
| 18 | for a in <a[href^='#']/> in me |
| 19 | set href to a's @href |
| 20 | set id to href.slice(1) |
| 21 | set el to document.getElementById(id) |
| 22 | if el exists |
| 23 | measure el |
| 24 | if its top <= 150 |
| 25 | set current to href |
| 26 | end |
| 27 | end |
| 28 | end |
| 29 | if current is not empty and current is not :lastHash |
| 30 | set :lastHash to current |
| 31 | call activate(current) |
| 32 | end |
| 33 | end |
| 34 | |
| 35 | on hashchange from window |
| 36 | if window.location.hash is not empty |
| 37 | call activate(window.location.hash) |
| 38 | end |
| 39 | end |
| 40 | |
| 41 | init |
| 42 | if window.location.hash is not empty |
| 43 | wait 50ms then call activate(window.location.hash) |
| 44 | end |
| 45 | end |
| 46 | |
| 47 | end |