coolbotic
coolbotic

Reputation: 56

Array Section JavaScript?

I have a button that then when clicked runs this function and want to to change elements in my html which have ids and loop and do this in order and am unsure why I am unable to do this! (Must use an array do this, in mind alternate methods to do this could help) All responses appreciated! :) Thanks James

function Example() {

                    var color = [
                        "Pink",
                        "Black",
                        "Orange"
                    ];

                    var ids = [
                        "Top",
                        "Mid",
                        "Bot"
                    ];



                for (i = -1, i != 3, i = i + 1) {
                     document.getElementById(ids[i]).style.background = color[i]

                }

Upvotes: 2

Views: 68

Answers (1)

dfsq
dfsq

Reputation: 193271

Your for-loop should have a condition and increment part separated with semicolon. With commas you basically only have initialization part. Then you need to start loop with i = 0 as it will be the first value in the loop. Also, don't forget var when declaring variables.

Try this:

for (var i = 0; i != 3; i = i + 1) {
    document.getElementById(ids[i]).style.background = color[i];
}

UPD. To add a delay (3s = 3000ms) between iterations you can do something like this:

for (var i = 0; i != 3; i = i + 1) {
    (function(index) {
        setTimeout(function() {
            document.getElementById(ids[index]).style.background = color[index];
        }, 3000 * index);
    })(i);
}

Read more about closures in loops.

Upvotes: 1

Related Questions