jQuery toggleClass example
Toggle class name on click in jQuery
by joshmoto
HTML
<div id="colors">
<div class="a"></div>
<div class="b"></div>
<div class="c"></div>
<div class="d"></div>
</div>
SCSS
#colors {
> DIV {
height: 50px;
}
.a {
background: cyan;
}
.b {
background: magenta;
}
.c {
background: yellow;
}
.d {
background: black;
}
}
JavaScript
// our colors
let colors = [{
'cls': 'a',
'background': 'cyan'
},
{
'cls': 'b',
'background': 'magenta'
},
{
'cls': 'c',
'background': 'yellow'
},
{
'cls': 'd',
'background': 'black'
}
];
// color array count
let color_count = colors.length;
// log our color count
console.log(color_count);
// colors div
const elem = $('#colors');
// increment var
let i = 0;
// our recolor function
let recolor = function() {
// each colors array as key value (object)
$.each(colors, function(key, obj) {
// increment
i++;
// if colors key is last key
if (key === (color_count - 1)) {
// log as end
//console.log('end');
$('[class="' + obj.cls + '"]', elem).attr('style', 'background: ' + colors[0].background + ' !important;');
setTimeout(function() {
// increment
i = 0;
recolor();
}, 1000);
} else {
//console.log(colors[key + 1]);
$('[class="' + obj.cls + '"]', elem).attr('style', 'background: ' + colors[i + 1].background + ' !important;');
}
});
}
recolor();