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
Sam Bell
4,410 PointsChange colour of header every time you scroll onto a black background
So I am building a site that has white background panels and black background panels. The header is fixed and the li items are black along with a black logo, however when you scroll onto a black background you cant see the header therefore I have set up some js that will change the header styles once you have scrolled to a black background element. However I cant figure out why it wont change back once you have scrolled off the black background?
Here is my code
if(document.body.querySelector('.blackBg')){
// getting all lines on page
var blackBgEl = document.querySelectorAll('.blackBg');
var headerEl = document.querySelector('header[role="banner"]');
window.addEventListener('scroll', function(){
for(i = 0; i < blackBgEl.length; i++){
var blackBgEls = blackBgEl[i];
// getting the position of the black background panel
var panelTopPos = blackBgEls.getBoundingClientRect().top;
var panelBottomPos = blackBgEls.getBoundingClientRect().bottom;
var scrolledDistance = window.pageYOffset;
if (scrolledDistance >= panelTopPos){
headerEl.classList.add('changeHeaderColour');
} else {
if(scrolledDistance >= panelBottomPos) {
headerEl.classList.remove('changeHeaderColour');
}
}
}
});
}
1 Answer
KRIS NIKOLAISEN
54,974 PointsIf scrolledDistance >= panelBottomPos won't it always be >= panelTopPos as well? Therefore your else statement will never execute.