Reputation: 79
I have a working code right here that randomly adds kvDisplay class on a list of divs every page load. The code below is particularly for 3 divs only.
var classes = ["kvDisplay", " ", " "];
classes.sort(function(){ return Math.random() - .5 });
$("#keyvisual .kvWrapper").each(function(){
$(this).addClass(classes.pop());
});
https://jsfiddle.net/m71xc5ty/
Instead of adding class randomly, how do I change it in a specific order?
Ex. Class kvDisplay will be added to the first child div of #keyvisual on first pageload, then it will be added to the second child on the next reload, and so on. If the kvDisplay class is on the third/last child, the class will go back to the first child after reload.
Upvotes: 0
Views: 51
Reputation: 1332
So you can use https://github.com/carhartl/jquery-cookie plugin to use cookies with jquery.
This code will help you to achieve it:
if ($.cookie("classes")) {
var classes = JSON.parse($.cookie('classes'));
} else {
var classes = ["kvDisplay1", "kvDisplay2", "kvDisplay3"];
}
console.log(classes);
$(document).ready(function () {
var i = 0;
$("#keyvisual .kvWrapper").each(function(){
$(this).addClass(classes[i]);
console.log(classes[i]);
i++;
});
var a = classes[0];
classes.shift();
classes.push(a);
$.cookie("classes", JSON.stringify(classes));
});
Upvotes: 1