0

I'm currently using a jQuery function to randomly assign one of a list of background colors to every element which has one of a list of CSS classes assigned to it:

$(document).ready(function() {
    var colors = ['color1', 'color2', 'color3'];
    $('.class1, .class2').each(function () {
        var hue = colors[Math.floor(Math.random() * colors.length)];
        $(this).css("background-color", hue);
    });
});

I would like to alter the function so that instead of assigning the colors at random, it assigns them in sequence, looping back to the beginning of the color array when there are more elements to assign colors to than colors to assign, i.e.:

<element1 class="class1" style="background-color: color1;"></element1>
<element2 class="class2" style="background-color: color2;"></element2>
<element3 class="class1" style="background-color: color3;"></element3>
<element4 class="class2" style="background-color: color1;"></element4>
<element5 class="class1" style="background-color: color2;"></element5>

Any suggestions as to where to start with this would be very much appreciated!

2
  • 2
    Maybe count the number of arrays, use a for loop on the classes then use a seperate counter and reset the counter when it equals the number of colours? Commented Aug 10, 2013 at 21:19
  • Thanks Liam. I'm not sure what you mean by counting the arrays though? Commented Aug 10, 2013 at 21:27

1 Answer 1

1

Try this:

$(document).ready(function () {
    var colors = ['#f00', '#0f0', '#00f'];
    var x = 0;
    $('.class1, .class2').each(function () {
        var hue = colors[x];
        x++;
        if (x == colors.length) {
            x = 0;
        }
        $(this).css("background-color", hue);
    });
});

Demo here

I didn't use a traditional for loop, but I made one myself by creating a variable x and adding it on .each(), and if it reaches the end of the color array I give it 0(zero) value again to start over.

Was this what you were looking for?

Sign up to request clarification or add additional context in comments.

1 Comment

That's brilliant, and a lot more elegant than the solution I was trying to write! Thanks for your help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.