In my Table of Contents, identified as #TableOfContents
, each href
points to either an h2 or h3 tag.
The issue I'm facing is that when the heading (h2 or h3) is observed by the intersection observer, the corresponding link in #TableOfContents
is highlighted by adding the class
side-active</code. However, once the longer content (like a <code>p
paragraph) after the heading enters the viewport, the highlight for that section is removed because the heading is no longer in view.
This is problematic because I want the section (h2, h3) to remain highlighted until the next h2 or h3 crosses the midpoint of the viewport.
Any suggestions on how to solve this?
window.addEventListener('DOMContentLoaded', () => {
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
const id = entry.target.getAttribute('id');
if (entry.intersectionRatio > 0) {
document.querySelector(`#TableOfContents a[href="#${id}"]`).classList.add('side-active');
} else {
document.querySelector(`#TableOfContents a[href="#${id}"]`).classList.remove('side-active');
}
});
});
toc = document.querySelectorAll('#TableOfContents a');
// get content so that link refer to it
toc.forEach(function (link) {
var id = link.getAttribute("href");
var element = document.querySelector(id);
observer.observe(element);
});
});
Highlighted Text When Heading is in Viewport
https://i.sstatic.net/vgiLh.png