When I press the "add section" button to create a new section, the intersection observer does not seem to observe it. Even when I try to run the observer again after pressing the button, it still doesn't work. I suspect that I need to reassign the `sections` variable in the code somewhere, but I'm unsure where exactly I should do this.
let sections = document.querySelectorAll("section");
let navList = document.getElementById("navbar__list");
const buildSecBtn = document.getElementById("newSection");
const main = document.querySelector("main");
let counter = 3;
const buildSection = () => {
counter++
const newSec = `<section id="section${counter}" data-nav="Section ${counter}">
<div class="landing__container">
<h2>Section ${counter}</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
</div>
</section>`
main.insertAdjacentHTML("beforeend", newSec);
};
const buildNav = () => {
navList.innerHTML ="";
sections = document.querySelectorAll("section");
sections.forEach(section => {
const navItem = `<li><a class="menu__link" data-nav="${section.id}" href="${section.id}">${section.dataset.nav}</a></li>`
navList.insertAdjacentHTML("beforeend",navItem)
});
};
buildNav();
let options = {
threshold: .7
};
const sectionObserver = (entries, Observer) => {
entries.forEach(entry => {
const activeLink = navList.querySelector(`[data-nav=${entry.target.id}]`)
if (entry.isIntersecting) {
entry.target.classList.add("your-active-class")
activeLink.classList.add("active__li")
} else {
entry.target.classList.remove("your-active-class")
activeLink.classList.remove("active__li")
};
});
};
let Observer = new IntersectionObserver(sectionObserver, options);
sections.forEach(section => {
Observer.observe(section)
});
buildSecBtn.addEventListener("click", () => {
sections = document.querySelector("section")
buildSection();
buildNav();
sectionObserver();
})
body {
background: rgb(136,203,171);
/* Additional CSS properties */
}
/* Copy and modify remaining CSS here */
<!DOCTYPE >
<html lang="en">
<head>
<!-- Metadata -->
</head>
<body>
<header class="page__header">
</header>
<main>
</main>
<footer class="page__footer">
</footer>
</body>
</html>