Reputation: 1137
I'm using a function on my website to randomly addClass to a div. works fine, but I can't find a way to not repeat the same class twice one after the other (cause sometimes the same class is added and we can think the code is not working)...
here is my jquery code :
$("#switch").click(function(){
var classes = ["vert", "escalier","reverse","demi_escalier","demi_escalier_2","ligne" ];
$("#logo").removeClass().addClass(classes[~~(Math.random()*classes.length)]);
});
can anybody help me with this ?
thanks
Upvotes: 3
Views: 1106
Reputation: 3207
if you want classes not repeat you can use following:
var classes = ["vert", "escalier", "reverse", "demi_escalier", "demi_escalier_2", "ligne"];
var classesCopy = classes.slice();
$('#switch').click(function() {
if (!classesCopy.length) {
classesCopy = classes.slice();
} // once alls classes used up it starts from beginning
var classToAdd = classesCopy.splice(Math.floor(Math.random() * classesCopy.length), 1);
$('.current-class').text('current class: ' + classToAdd);
$('#logo').removeClass().addClass(classToAdd+'');
});
#logo {
width: 100px;
height: 100px;
background: green;
}
<div class='current-class'></div>
<div id='logo'></div>
<button id='switch'>switch</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
Upvotes: 1
Reputation: 24965
//put it in an IIFE so the variables are scoped down
(function(){
//constants, don't need to declare them in the click function over and over
var classes = ["vert", "escalier","reverse","demi_escalier"
,"demi_escalier_2","ligne" ];
//keep track of the last class used, -1 initial so no chance of mismatch
var lastNumber = -1;
var $logo = $("#logo");
$("#switch").on('click', function() {
//get a new index
var nextClass = Date.now() * 100 % classes.length;;
//while they match, keep getting a new one
while (nextClass === lastNumber) {
nextClass = Date.now() * 100 % classes.length;
}
$logo.removeClass().addClass(classes[nextClass]);
//save it off so we can do the double check again on the next execution
lastNumber = nextClass;
});
})();
Upvotes: 0