Brad Vanderbush Brad Vanderbush - 1 year ago 29
jQuery Question

Rotate multiple classes through multiple elements on the DOM

As I click the button the classes would rotate up or down through each div. so far all I can do is rotate the classes, but it only rotates the classes for the same div.





var classes = ['a', 'b', 'c']; // the different classes to rotate through each div




$('div').each(function() { // the div needs to rotate classes over and over
var i = 0;

$('button').click(function() {
$('div').removeClass( classes[ i ] );
i = ++i % classes.length;
$('div').addClass( classes[ i ] );
});
});

div { color:white; margin: 4px; width: 100px; height: 100px; }
.a {
background-color: blue;
}

.b {
background-color: red;
}

.c {
background-color: green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="a"></div> //class change on click to b, than c, back to a..
<div class="b"></div> //this change to c than a than b ..
<div class="c"></div> // basically these classes always rotate

<button>
rotate
</button>




Answer Source

You can use "Shift" and "Push" for shifting indexes. I have updated code in snippet. Please find below.

var classes = ['a', 'b', 'c'];  // the different classes to rotate through each div

   // the div needs to rotate classes over and over
    
    
    $('button').click(function() {
    var i = 0;
  debugger;
    $('div').each(function(key) { 
    var remove = classes.shift();
    $(this).removeClass()
     classes.push(remove)
    $(this).addClass(classes[i]);
      i++;
      
    });
});
div { color:white; margin: 4px; width: 100px; height: 100px; }
.a {
    background-color: blue;
}

.b {
    background-color: red;
}

.c {
    background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="a"></div>  //class change on click to b, than c, back to a..
<div class="b"></div>  //this change to c than a than b ..
<div class="c"></div> // basically these classes always rotate

<button>
rotate
</button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download