JSFiddle - React, Tailwind, and code Playground
HTML
<div class="stoplight off"></div>
<div class="stoplight green"></div>
<div class="stoplight red"></div>
CSS
.stoplight {
width: 50px; height: 50px;
border: 1px solid black;
}
.stoplight.green {
background: green;
}
.stoplight.yellow {
background: yellow;
}
.stoplight.red {
background: red;
}
JavaScript
$('.stoplight').click(function() {
var lights = ['off','green','yellow','red'];
// find current status
var status = $(this).attr('class').replace('stoplight ','');
// get current position in array
var position = $.inArray(status, lights);
// get new position
var position_new;
// -1 because array index starts with 0
if (position == lights.length-1) {
// if it's at the end, go to the beginning
position_new = 0;
} else {
// else take the next status in the array
position_new = position+1;
}
// get the new status, based on position
var status_new = lights[position_new];
// switch classes
$(this).toggleClass(status+' '+status_new);
});