Skip to content

Commit a79dc29

Browse files
Create details-anchor.js (#219)
1 parent faab40f commit a79dc29

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
})();

0 commit comments

Comments
 (0)