3

I have to make a board as an assignment which lights up 1 by 1 like the sci-fi movie “Close Encounters of the Third Kind”. The main objective here is to get specific blocks to light up in a specific order with 2 second interval between them this is the code I have done now:

$(document).ready(function () {

    var colorBlocks = [
        'yellow',
        'green',
        'blue',
        'white',
        'orange'
    ]

    $.each(colorBlocks, function (i) {
        $('#' + this).css("background", this);
        // When you use the alert you can see the boxes change color one by one
        // alert(something);
    });

});

but this doesn't seem to work it changes the colour of all the boxes at once unless if you alert(something);

can anyone help?

RyanM
  • 751
  • 5
  • 20

3 Answers3

1

I think you want something like this:

$.each(colorBlocks, function (i) {
    setTimeout(function() {
        $('#' + this).css("background", this);
    }.bind(this), i * 2000);
});

Why i * 2000?

i is the iteration's index, so it'll wait i * 2000 ms for each call for the next "animation" to occur.

baao
  • 71,625
  • 17
  • 143
  • 203
  • 1
    This is what I would suggest doing as well. – Travis J Feb 08 '16 at 21:24
  • 2
    it says I have to wait 6 minutes before i can accept your question – RyanM Feb 08 '16 at 21:25
  • how would I get the function to run continously ? – RyanM Feb 08 '16 at 22:03
  • What do you mean? To have it restart all the time? @techedryan – baao Feb 08 '16 at 22:03
  • yeah to restart it so after it ends it re-runs again @Michael – RyanM Feb 08 '16 at 22:05
  • not like that it needs to be so that the function just keeps repeating itself over and over again continously without stopping – RyanM Feb 08 '16 at 22:12
  • It does, it's just not visible in the fiddle. Can you try it that way with your actual code please. The problem is that all the divs allready have their background color in the fiddle. You can make their backgrounds transparent again so that the animation is visible more often – baao Feb 08 '16 at 22:14
  • please open your console and look at this @techedryan https://jsfiddle.net/usqq41to/1/ – baao Feb 08 '16 at 22:16
  • oh yeah i see but how would i get the colours to clear and come back on dissapear and redo the flow – RyanM Feb 08 '16 at 22:22
0

This should work

$(document).ready(function () {
    var colorBlocks = [
        'yellow',
        'green',
        'blue',
        'white',
        'orange'
    ];

    $.each(colorBlocks, function (index, key) {
          var selector = $("#" + key);
          setTimeout(function () {
               selector.css("background", key);
          }.bind(this), index * 2000);
    });
});

JSBin: https://jsbin.com/gilemuzade/1/edit

JazzCat
  • 4,243
  • 1
  • 26
  • 40
-1

do a setInterval and increase the number every 2 seconds and call the function that shows your block.

Medda86
  • 1,582
  • 1
  • 12
  • 19