0

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);});
}
pjldesign
  • 387
  • 1
  • 3
  • 17
  • instead of jQuery, why not take advantage of modern JS and use an [intersection observer](https://developer.mozilla.org/docs/Web/API/Intersection_Observer_API), where you trigger any code you like based on "is thing X (almost) in view to the user?" – Mike 'Pomax' Kamermans Feb 13 '21 at 02:33
  • Was looking into it (that and MutationObserver) but i'm on crazy deadline and figured it would be easier to extend current working code. – pjldesign Feb 13 '21 at 02:58
  • Edited: using Intersection Observer API but no/limited results. What am I doing wrong? – pjldesign Feb 13 '21 at 06:06
  • Without an edit that shows your new code in an additional code block, no way to tell? – Mike 'Pomax' Kamermans Feb 13 '21 at 14:51

0 Answers0