2

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]

                }
coolbotic
  • 56
  • 2
  • 7

1 Answers1

1

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.

Community
  • 1
  • 1
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • Changed the my code thou and yet is still is not changing so not sure if its the loop not working still as when just setting i = 0 and taking away the loop it changes to the correct color so .... if you can help thanks ! James – coolbotic Dec 05 '15 at 11:20
  • Taking that back my error (typo) would you by any chance know how to time this o it happens one by one ? – coolbotic Dec 05 '15 at 11:22
  • *"happens one by one"* how it exactly? – dfsq Dec 05 '15 at 11:31
  • @coolbotic If you want to delay things, use `setInterval` or `setTimeout`. – Barmar Dec 05 '15 at 11:35
  • So like the loop runs once then waits (3sec) then goes again changing the next one! Also how would make to loop start again once its finished? Sorry for all the questions. – coolbotic Dec 05 '15 at 11:36
  • @Barmar an could you give an example of that ? – coolbotic Dec 05 '15 at 11:37
  • Thanks so for the help all working now! Just trying to understand the code and unsure what "index" is doing here !! – coolbotic Dec 05 '15 at 23:26
  • Read link I posted. This is anonymous function and index is the value of `i` passed as a parameter to this function. This is closure. – dfsq Dec 05 '15 at 23:32