I want to use an intersection observer to see when a certain part of my page has been reached. My page is divided by a few sections with ids, for example #section1, #section2, #section3 etc.
At the top of my page is a sticky menu with buttons to navigate to each section. I want to highlight the button that a user is currently viewing.
So when scrolling to section 1, highlight section1 button but when scrolling further down, keep it highlighted until section2 has been reached (with a little offset, maybe 300px so a user scrolls a bit past the divider until it highlights), then highlight that button.
How can this be done?
I made this:
function selectElementById(idname) {
return document.querySelector(`#${idname}`);
}
const sections = [
selectElementById('top'),
selectElementById('bestellen'),
selectElementById('informatie'),
selectElementById('inspiratie'),
selectElementById('reviews'),
];
const navItems = {
top: selectElementById('topbtn'),
bestellen: selectElementById('bestellenbtn'),
informatie: selectElementById('informatiebtn'),
inspiratie: selectElementById('inspiratiebtn'),
reviews: selectElementById('reviewsbtn'),
};
const observerOptions = {
root: null,
rootMargin: '-175px 0px 0px 0px',
threshold: 0.7,
};
function observerCallback(entries, observer) {
entries.forEach((entry) => {
if (entry.isIntersecting) {
// get the nav item corresponding to the id of the section
// that is currently in view
const navItem = navItems[entry.target.id];
// add 'active' class on the navItem
navItem.classList.add('activeprodmenu');
// remove 'active' class from any navItem that is not
// same as 'navItem' defined above
Object.values(navItems).forEach((item) => {
if (item != navItem) {
item.classList.remove('activeprodmenu');
}
});
}
});
}
const observer = new IntersectionObserver(observerCallback, observerOptions);
sections.forEach((sec) => observer.observe(sec));
But I get this error: Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'.