I have a function that adds a class current
to a menu item when its corresponding section comes into view. How would I go about also adding/removing different classes to body
as well, based on currently visible section?
Edit: Per suggestion got it working finally with Intersection Observer but still trying to figure out how to add and swap classes to body:
function setColorScheme() {
const nav = (entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting && entry.intersectionRatio >= 0.55) {
document.querySelector('li.current').classList.remove('current');
var id = entry.target.getAttribute('id');
var newLink = document.querySelector(`[href$='#${id}']`).parentElement.classList.add('current');
//returning error
var newClass = $('body.home').classList.add('.' + id);
}
});
}
const options = {
threshold: 0.55,
rootMargin: '150px 0px'
};
const observer = new IntersectionObserver(nav,options);
const sections = document.querySelectorAll('section.op-section');
sections.forEach((section) => {observer.observe(section);});
}