Search code examples
javascriptcssarraysonclickbackground-color

With single button, how to change div background color in order listed, not randomly


I'm working with the code below to change the background color of the div on button click. It chooses the colors randomly (math.random), but I'd like it to choose the colors in listed order (red > blue > yellow > etc.). Can anyone help me with this? Thanks in advance!

<style>
#changecolor2 {
    height: 100px;
    width: 100px;
}
</style>

<script>
var colors = ["red", "blue", "yellow", "green", "orange", "black", "cyan", "magenta"]
function changeColor() {
    var col = document.getElementById("changecolor");
    col.style.backgroundColor = colors[Math.floor((Math.random()*8)+1)];
}
</script>

<body>
<div id="changecolor2"></div>
<button onclick="changeColor();">change color</button>
</body>

Solution

  • var colors = ["red", "blue", "yellow", "green", "orange", "black", "cyan", "magenta"];
    var colorIndex = 0;
    function changeColor() {
        var col = document.getElementById("changecolor2");
        if( colorIndex >= colors.length ) {
            colorIndex = 0;
        }
        col.style.backgroundColor = colors[colorIndex];
        colorIndex++;
    }
    window.onload = changeColor;
    

    Fiddle : http://jsfiddle.net/aslancods/6S46U/