Search code examples
javascriptbabeljs

Change fixed logo color on scroll depending of current section class?


I am trying to change the color of my fixed SVG logo based on the current section you scroll. For instance, if you scroll inside a section with a class "intro" or "projects" I want to change the logo color with a CSS class.

So, on entering the section and at END of the section scrolling from top and bottom to remove and add the previous class.

Basically, I have an array of all sections looping through them with an EventListener scroll which should toggle the logo class on a scroll and IF inside a section or not.

Can someone help me out?

My code:

(() => {
    const logo = document.querySelector('.logo');
    const sections = document.querySelectorAll('section');

    if(!sections.length) {
        return;
    }

    const onPageScroll = () => {
        sections.forEach(section => {
            console.log(section);
            
        });
    }

    window.addEventListener('scroll', onPageScroll);
})();

Solution

  • I believe one of these pens should help you. What you're trying to do is a scroll spy.

    From the second pen:

    const spyScrolling = ( ) => {
      const sections = document.querySelectorAll( '.hero-bg' );
    
      window.onscroll = ( ) => {
        const scrollPos = document.documentElement.scrollTop || document.body.scrollTop;
    
        for ( let s in sections )
          if ( sections.hasOwnProperty( s ) && sections[ s ].offsetTop <= scrollPos ) {
            const id = sections[ s ].id;
            document.querySelector( '.active' ).classList.remove( 'active' );
            document.querySelector( `a[href*=${ id }]` ).parentNode.classList.add( 'active' );
          }
      } 
    }
    

    There are plenty of other examples available out there, you just have to know the right keywords.