I have a bunch of text that is split into headings <h2> and <h3> and paragraphs <p>. The <h2> have an ID assigned to them that matches a navigation pane, which is just a simple table of contents in a list form with links <ul> and <li> and <a>.
For example: <h2 id="test-1">Test 1</h2>
Correlates to: <li><a href="#test-1">Test 1</a></li>
The goal is to use the IntersectionObserver API to highlight the table of contents when the users scrolls down the page.
For example, the .active-content class and the .active-content-left-border class both get applied in the relevant places to make the table of contents highlighted and turned green.
Please observe the following Javascript. As you can see if the heading <h2> is intersecting isIntersecting, it adds the class to the element, which altars the colour and adds a border.
However, the issue I'm experiencing is that if there are more than one heading <h2> on the screen, it throws the whole script off.
const tableofcontents = document.querySelectorAll("#sub-content-right-table-of-contents-list li a");
const tableofcontentsleftborders = document.querySelectorAll("#sub-content-right-table-of-contents-list li")
const headings = document.querySelectorAll("#sub-content-main-text h2")
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
const index = Array.from(headings).indexOf(entry.target)
if (entry.isIntersecting) {
tableofcontents[index].classList.add("active-content")
tableofcontentsleftborders[index].classList.add("active-content-left-border")
} else if (!entry.isIntersecting) {
tableofcontents.forEach(tableofcontent => {
tableofcontent.classList.remove("active-content")
})
tableofcontentsleftborders.forEach(tableofcontentsleftborder => {
tableofcontentsleftborder.classList.remove("active-content-left-border")
})
}
})
}, {
threshold: 0.25,
})
headings.forEach(heading => {
observer.observe(heading)
})
So my question is, if there are two headings on the screen - how do I make it so that the very top header is the one that stipulating the addition of the class?