jQuery Change BG Color with Button Click

by nickadeemus2002

HTML

<button style="margin:30px">Change color</button>

<div style="margin:60px"><span id="test" class="green"></span></div>

CSS

.green{ background:green}
.yellow{background:yellow;}
.red{background:red;}
span{ display:inline-block; width:20px; height:20px}

JavaScript

$(function() {

    var colors = ['green', 'yellow', 'red'];
    var curr_color = 0;
    $('button').click(function() {
        
        alert('current color: '+curr_color);
        curr_color = (curr_color + 1 < 3) ? curr_color + 1 : 0;
        alert('new current color:' + curr_color);
        $('#test').removeClass().addClass(colors[curr_color])
    });

});