Highlight TOC with IntersectionObserver API

pull/11/head
Folyd 2 years ago
parent c9fe064b03
commit c2ba14f473

@ -37,9 +37,9 @@
</h3>
<div>
<a class="github-button" href="https://github.com/huhu/juice" data-size="large" data-show-count="true"
aria-label="Star huhu/juice on GitHub">Star</a>
aria-label="Star huhu/juice on GitHub">Star</a>
<a class="github-button" href="https://github.com/huhu/juice/fork" data-size="large"
data-show-count="true" aria-label="Fork huhu/juice on GitHub">Fork</a>
data-show-count="true" aria-label="Fork huhu/juice on GitHub">Fork</a>
</div>
</section>
<img class="hero-image" style="width: 50%" src="{{ get_url(path="juice.svg") }}">
@ -52,6 +52,7 @@
.hero section {
padding: 0 5rem;
}
@media screen and (max-width: 768px) {
.hero section {
padding: 0 2rem;
@ -114,38 +115,28 @@
{% endblock footer %}
</body>
<script>
function highlightNav(heading) {
let pathname = location.pathname;
const scrollHandler = entries => {
// Find the first entry which intersecting and ratio > 0.9 to highlight.
let entry = entries.find(entry => {
return entry.isIntersecting && entry.intersectionRatio > 0.9;
});
if (!entry) return;
document.querySelectorAll(".toc a").forEach((item) => {
item.classList.remove("active");
});
document.querySelector(".toc a[href$='" + pathname + "#" + heading + "']").classList.add("active");
}
let currentHeading = "";
window.onscroll = function () {
let h = document.querySelectorAll("h1,h2,h3,h4,h5,h6");
let elementArr = [];
h.forEach(item => {
if (item.id !== "") {
elementArr[item.id] = item.getBoundingClientRect().top;
}
});
elementArr.sort();
for (let key in elementArr) {
if (!elementArr.hasOwnProperty(key)) {
continue;
}
if (elementArr[key] > 0 && elementArr[key] < 300) {
if (currentHeading !== key) {
highlightNav(key);
currentHeading = key;
}
break;
}
// let url = new URL(`#${entry.target.id}`);
let link = document.querySelector(`.toc a[href$="${decodeURIComponent(`#${entry.target.id}`)}"]`)
if (link) {
link.classList.add("active");
link.scrollIntoView({ behavior: "auto", block: "nearest" });
}
}
};
// Set -100px root margin to improve highlight experience.
const observer = new IntersectionObserver(scrollHandler, { threshold: 1 });
let items = document.querySelectorAll('h1,h2,h3,h4,h5,h6');
items.forEach(item => observer.observe(item));
</script>
</html>
</html>
Loading…
Cancel
Save