canyin canyin - 5 months ago 12
jQuery Question

JavaScript - Background change with CSS Class and setInterval method

I'm fairly new with JavaScript and I would like to make an automatic background changer with timed intervals and CSS class changes. At the moment my code doesn't cycle two backgrounds as intended. Can you guys check what's wrong with it?

Thanks!

$(document).ready(function() {

var switcher = 0;

var counter = setInterval(count, 2000);

function count() {
switcher = switcher + 1;
if (switcher >= 2) {
switcher = 0;
return;
};
};


switch (switcher) {

case 0:
$("#main-content").removeClass("background1");
$("#main-content").addClass("background3");
break;

case 1:
$("#main-content").removeClass("background3");
$("#main-content").addClass("background1");
break;


};
});

Answer

Move switch() statement into interval function callback. remove return as well.

function count() {
    switcher = switcher + 1;
    if (switcher >= 2) {
      switcher = 0;
    };
    switch (switcher) {

        case 0:
          $("#main-content").removeClass("background1");
          $("#main-content").addClass("background3");
          break;

        case 1:
          $("#main-content").removeClass("background3");
          $("#main-content").addClass("background1");
          break;
    };

};