\$\begingroup\$
\$\endgroup\$
4
I want to change the background color of each section of the page when the user scrolls. The code works but I feel like it's too inefficient
var colors = ['blue','yellow','green','purple','brown'];
var myScope;
var sections = [$('#section1'),$('#section2'),$('#section3'),$('#section4'),$('#section5')];
var sectionTop = [$('#section1').offset().top, $('#section2').offset().top, $('#section3').offset().top, $('#section4').offset().top, $('#section5').offset().top];
var zeus;
$(window).scroll(function () {
myScope = $(window).scrollTop() + 300;
if (myScope >= sectionTop[0] && myScope < sectionTop[1]) {
sections[0].css('background-color', colors[0]);
} else {
sections[0].css('background-color', 'white');
};
if (myScope >= sectionTop[1] && myScope < sectionTop[2]) {
sections[1].css('background-color', colors[1]);
} else {
sections[1].css('background-color', 'white');
};
if (myScope >= sectionTop[2] && myScope < sectionTop[3]) {
sections[2].css('background-color', colors[2]);
} else {
sections[2].css('background-color', 'white');
};
if (myScope >= sectionTop[3] && myScope < sectionTop[4]) {
sections[3].css('background-color', colors[3]);
} else {
sections[3].css('background-color', 'white');
};
if (myScope >= sectionTop[4] ) {
sections[4].css('background-color', colors[4]);
} else {
sections[4].css('background-color', 'white');
};
});
I also tried to replace all those "if" with a "for" loop but it doesn't work, it doesn't pop any errors or anything, it just doesn't work.
for (var i = 0; i < sections.length-1; i++) {
var j = i++;
if (myScope >= sectionTop[i] && myScope < sectionTop[j]) {
sections[i].css('background-color', colors[i]);
} else {
sections[i].css('background-color', 'white');
};
};
200_success
145k22 gold badges190 silver badges478 bronze badges
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
Heres your code slimmed down, the problem you were having with the loop was that you weren't getting offset().top
of your sectionTop[i]
.
var myScope = zeus = false;
var colors = ['blue','yellow','green','purple','brown'];
var sectionId = '#section';
var sections = 5;
$(window).on('scroll', function() {
myScope = $(window).scrollTop() + 300;
for (var i = sections; i >= 0; i--) {
var sid = i > 0 ? i : 1;
var css = 'white';
if(myScope >= $(sectionId + sid).offset().top
&& myScope < $(sectionId + sid).offset().top) {
css = colors[i];
}
$(sectionId + sid).css('background-color', css);
}
});
-
\$\begingroup\$ At least only read
$(sectionId + sid).offset().top
once \$\endgroup\$Jamiec– Jamiec2016年07月29日 16:03:24 +00:00Commented Jul 29, 2016 at 16:03
lang-css
id
that starts withsection
you can use$('[id^="section"]')
\$\endgroup\$