Boris Kozarac Boris Kozarac - 2 years ago 64
Javascript Question

Change class every few seconds from values in array

I am trying to change class on a div every 3 seconds. Classes are in array, previous class should be removed and next one added. "First" should be first, then "second", then "third" and back to loop.

I know how to

but I am stuck on part where code should put the next available class from array.

<div id="main"></div>

jQuery(document).ready(function ($) {
var images = ['first', 'second', 'third'];

function changeBackground() {
var className = $('#main').attr('class');
if (className == null)
className = images[0];

$('#main').removeClass(function () {
var newClass = // find value in array and take next value, if end of array get first

setInterval(changeBackground, 2000);

Answer Source

You don't need to pass a function into removeClass. You do need to keep track of what class you're on so you can move to the next on the next timer tick. I've explained in the comments:


    var images = ['first', 'second', 'third'];
    // Remember where we are in the array, start just before the first entry
    var classIndex = -1;

    function changeBackground() {

        // Grab the element
        var main = $("#main");

        // If this isn't the first time, remove the previous class
        if (classIndex >= 0) {

        // Update the index, wrapping around when we reach the end of the array
        classIndex = (classIndex + 1) % images.length;

        // Add the new class

    setInterval(changeBackground, 2000);


Notes about the above:

  • It's obviously much more compact without explanatory comments
  • It won't wipe out other, unrelated classes on #main (whereas solutions using removeClass() with no arguments will)

Here's a more compact version if you're into that kind of thing. I wouldn't suggest compacting it to quite this degree, though. :-)

    var classIndex = 0, images = ['first', 'second', 'third'];
    setInterval(function () {
            .addClass(images[classIndex = (classIndex + 1) % images.length]);
    }, 2000);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download