How to loop over an array of colors to change background on key(press/down)

Internet. Forgive me if this isn't somehow more relevant to others but I'll leave this here in case it's a valid question.

I am trying to create a textarea field in which every time and anytime the user presses a key (a-z), it will trigger a background color change (listed in an array). I've been doing this with JQuery and I think I'm close(?) but every time I run my code and press a key, the last item in the array is the only color that comes up. I thought to use a conditional with the for loop, but I wouldn't know where to put it--if it's even necessary. What am I doing wrong? Also, should I set "x = color[0]" instead?

$(document).ready(function() {
    var colors = ["#FFF0CB", "#FFECD1", "#FFE9DA", "#FFE7E4"];
    $("textarea").keydown(function() {
        for (x = 0; x < colors.length; x++;) {
            $("textarea").css("background-color", colors[x]);
        };
    });
});

JSFiddle

Answers 1

  • var colors = ["#FFF0CB", "#FFECD1", "#FFE9DA", "#FFE7E4"];
    var length = colors.length;
    $(document).ready(function() {
    var x = 0
    $("textarea").keydown(function() {
    $("textarea").css("background-color", colors[x]);
    if (x < length) {
      x++;
    } else if (x >= length) {
      x = 0
     }
     });
    })
    

Related Articles