Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Sam Bell
Sam Bell
4,410 Points

Switch between different header designs when you scroll down the page?

Hello

I am creating a website that has black sections and white sections. The header needs to be the black version on a white section and a white version on a black section. I have given each section a data-header="white" data-header="black"

Here is some code I have started, could someone help me with what else I need to do please?

var headerChangeEl = document.body.querySelectorAll('.headerChange'); var bannerHeight = document.querySelector('header[role="banner"]').getBoundingClientRect().height;

window.addEventListener('scroll', function(){

for(i = 0; i < headerChangeEl.length; i++){

    var headerChangesElements = headerChangeEl[i];
    var headerColor = headerChangesElements.getAttribute('data-header');
    var headerPos = headerChangesElements.getBoundingClientRect().top;          

    var scrolledDistance = window.pageYOffset - headerPos;

    if (scrolledDistance){

        //something here

    } else {


    }   

}

});

1 Answer

Steven Parker
Steven Parker
231,007 Points

It looks like you need to compare scrolledDistance to the section height, or just make sure to process only the first one that is not negative. Perhaps something like this:

    if (scrolledDistance > 0) {
        whiteHeader.style.display = headerColor == "white" ? "" : "none";
        blackHeader.style.display = headerColor == "black" ? "" : "none";
        break;
    }
    // no "else" needed

If you need more specific help, be sure to include the complete code including HTML and CSS. Also be sure to use the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area. :arrow_heading_down:   Or watch this video on code formatting.

Sam Bell
Sam Bell
4,410 Points

Thanks for your help!