Home > other >  How to change the element class when the last one targets, and stays over other element?
How to change the element class when the last one targets, and stays over other element?

Time:05-17

The project has the sticky menu with the white svg logo. When the sticky menu over the black section menu should stay white, if over the black section the logo should convert to the black. I tried a lot of variant for goal this. But all of them does not work properly. I olso tried to use old jQuery library: background-check but it does not work at all. Here is the last variant I created:

$(window).scroll(function() {

        let headerLogo = $("#header_logo");
        let overlaySection = $("#overlay-section");

        let headerLogo_top = headerLogo.offset().top;
        let headerLogo_bottom = headerLogo_top   headerLogo.height();

        let overlaySection_top = overlaySection.offset().top;
        let overlaySection_bottom = overlaySection_top   overlaySection.height();


        let services = $("#services");
        let services_top = services.offset().top;
        let services_bottom = services_top   services.height();

    
        if (headerLogo_bottom >= overlaySection_top && headerLogo_top < overlaySection_bottom) {
            headerLogo.addClass('black_active')
        }else if(headerLogo_bottom >= services_top && headerLogo_top < services_bottom){
            headerLogo.removeClass('black_active')
        }
        else{
            headerLogo.removeClass('black_active')
        }

    });

And it almost works but not properly because the class changed to early and logo color changed from black to whit when it does not target the next black block. Maybe there is some old but good works jQuery library please advise I need to figure out in this issue.

CodePudding user response:

Instead of addClass and removeClass, have you tried the following?

headerLogo.classList.toggle('black_active');

For some reason I also always get stuck with the other two, but this always seems to work.

  • Related