File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Auto-open a <details> element when the URL hash points to an anchor
3+ * inside or immediately before it.
4+ */
5+ ( function ( ) {
6+ "use strict" ;
7+
8+ function openDetailsForHash ( ) {
9+ var hash = window . location . hash ;
10+ if ( ! hash ) return ;
11+
12+ var target = document . querySelector ( hash ) ;
13+ if ( ! target ) return ;
14+
15+ // The anchor <span> may be wrapped in a <p> by the markdown parser.
16+ // Walk up through parents checking siblings to find the closest <details>.
17+ var details = target . closest ( "details" ) ;
18+ if ( ! details ) {
19+ var el = target ;
20+ while ( el && ! details ) {
21+ var next = el . nextElementSibling ;
22+ if ( next && next . tagName === "DETAILS" ) {
23+ details = next ;
24+ break ;
25+ }
26+ // Walk up to parent and check its next sibling
27+ el = el . parentElement ;
28+ }
29+ }
30+ if ( ! details ) return ;
31+
32+ details . open = true ;
33+
34+ // Scroll the target into view after a brief delay to let the browser
35+ // lay out the newly-opened content.
36+ setTimeout ( function ( ) {
37+ target . scrollIntoView ( { behavior : "smooth" , block : "start" } ) ;
38+ } , 100 ) ;
39+ }
40+
41+ // Run on initial load and when hash changes (e.g. clicking in-page links)
42+ if ( document . readyState === "loading" ) {
43+ document . addEventListener ( "DOMContentLoaded" , openDetailsForHash ) ;
44+ } else {
45+ openDetailsForHash ( ) ;
46+ }
47+ window . addEventListener ( "hashchange" , openDetailsForHash ) ;
48+ } ) ( ) ;
You can’t perform that action at this time.
0 commit comments