Change the background color of each section of the page when the user scrolls 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 &gt;= sectionTop[0]  &amp;&amp; myScope &lt; sectionTop[1]) {
    sections[0].css('background-color', colors[0]);
    } else {
    sections[0].css('background-color', 'white');
    };

    if (myScope &gt;= sectionTop[1]  &amp;&amp; myScope &lt; sectionTop[2]) {
    sections[1].css('background-color', colors[1]);
    } else {
    sections[1].css('background-color', 'white');
    };

    if (myScope &gt;= sectionTop[2]  &amp;&amp; myScope &lt; sectionTop[3]) {
    sections[2].css('background-color', colors[2]);
    } else {
    sections[2].css('background-color', 'white');
    };

    if (myScope &gt;= sectionTop[3]  &amp;&amp; myScope &lt; sectionTop[4]) {
    sections[3].css('background-color', colors[3]);
    } else {
    sections[3].css('background-color', 'white');
    };

    if (myScope &gt;= 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 &lt; sections.length-1; i++) {
        var j = i++;
        if (myScope &gt;= sectionTop[i] &amp;&amp; myScope &lt; sectionTop[j]) {
        sections[i].css('background-color', colors[i]);
        } else {
        sections[i].css('background-color', 'white');
        };
    };
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 &gt;= 0; i--) {
   var sid = i &gt; 0 ? i : 1;
   var css = 'white';
   if(myScope &gt;= $(sectionId + sid).offset().top 
   &amp;&amp; myScope &lt; $(sectionId + sid).offset().top) {
    css = colors[i];
   }

   $(sectionId + sid).css('background-color', css);
}

});