forked from greenelab/lab-website-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanchors.js
47 lines (41 loc) · 1.38 KB
/
anchors.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
creates link next to each heading that links to that section.
*/
{
const onLoad = () => {
// for each heading
const headings = document.querySelectorAll(
"h1[id], h2[id], h3[id], h4[id]"
);
for (const heading of headings) {
// create anchor link
const link = document.createElement("a");
link.classList.add("icon", "fa-solid", "fa-link", "anchor");
link.href = "#" + heading.id;
link.setAttribute("aria-label", "link to this section");
heading.append(link);
// if first heading in the section, move id to parent section
if (heading.matches("section > :first-child")) {
heading.parentElement.id = heading.id;
heading.removeAttribute("id");
}
}
};
// scroll to target of url hash
const scrollToTarget = () => {
const id = window.location.hash.replace("#", "");
const target = document.getElementById(id);
if (!target) return;
const offset = document.querySelector("header").clientHeight || 0;
window.scrollTo({
top: target.getBoundingClientRect().top + window.scrollY - offset,
behavior: "smooth",
});
};
// after page loads
window.addEventListener("load", onLoad);
window.addEventListener("load", scrollToTarget);
window.addEventListener("tagsfetched", scrollToTarget);
// when hash nav happens
window.addEventListener("hashchange", scrollToTarget);
}