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.
Arrays are lists of any kind of data, including other arrays. Each item in the array has an index — a number — which can be used to retrieve an element from the array.
Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. But, JavaScript arrays are best described as arrays. Arrays use numbers to access its "elements".
An array is an object that can store multiple values at once. For example, const words = ['hello', 'world', 'welcome']; Here, words is an array.
{} is shorthand for creating an empty object. You can consider this as the base for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array . [] is shorthand for creating an empty array.
First you need to define global i variable, that will keep your current index. Than check if it's value extends array length, if so, than you should reset it, to the array start.
var colors = ["purple", "yellow", "black"];
var i = 0; // define global i variable
function changeColor()
{
document.body.style.backgroundColor = colors[i++];
if(i >= colors.length)
{
i = 0;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With