Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Javascript about array.

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.

like image 748
codecodeNinja Avatar asked Aug 12 '15 07:08

codecodeNinja


People also ask

What is an array in HTML?

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.

What is array () in JavaScript?

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".

What is an array in JavaScript with example?

An array is an object that can store multiple values at once. For example, const words = ['hello', 'world', 'welcome']; Here, words is an array.

What is {} and [] in JavaScript?

{} 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.


1 Answers

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;
    }
}
like image 198
Beri Avatar answered Nov 12 '22 12:11

Beri