Exercise (02) - Solution

Supply the <div> element with another style by switching its css class per button click. Each click should use another css class from the provided array.

by bombo

HTML

<div id="target">Style me!</div>
<div>
    <button>Switch style</button>
</div>

CSS

.style1 {
    border: 1px dashed red;
    font-family: monospace;
}

.style2 {
    border: 2px solid blue;
    font-family: fantasy;
}

.style3 {
    background: black;
    color: yellow;
    padding: 10px;
}

.style4 {
    letter-spacing: 10px;
    border: 1px dotted black;
}

JavaScript

$(document).ready(function () {
    var styles = ['style1', 'style2', 'style3', 'style4'],
        index = 0,
        last = '',
        next = 'style1';
    
    $('button').click(function () {
        $('#target').removeClass(last);
        $('#target').addClass(next);
        index = (index === 3 ? 0 : index + 1);
        last = next;
        next = styles[index];
    });
});