I am still new to JavaScript. I need to create a button in html and allow the user to click the button to change the specify body background color.
var colors = ["purple", "yellow", "black"];
Above is the given array in the JavaScript. If the user click more than 3 times (after blue color), the green color will be selected again.
<form>
<p><input type="button" value="Change Color" name="B1" onclick="changeColor()"></p>
</form>
I roughly write the function for the button, but i did not know how i can assign the color from the array to the background color
function changeColor()
{
document.body.style.backgroundColor="colors[i]";
i++
if(i >=2)
{
i = 0;
}
}
Hope someone can correct my code.
var i = 0;somewhere outsidechangeColor. Next just usedocument.body.style.backgroundColor = colors[i];.