Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery make rainbow pattern with list

my html

<div id="mainMenu">
    <span>Thing 1</span>
    <span>Thing 2</span>
    <span>Thing 3</span>
    <span>Thing 4</span>
    <span>Thing 5</span>
    <span>Thing 6</span>
    <span>Thing 7</span>
</div>

how can i get thing 6 and thing 7 to have colors? it stops at them because it does 1-5

colors = ['red','orange','yellow','green', 'blue']; //roygbiv

$('#mainMenu span').each(function(i){
    this.style.color = colors[i];
});
like image 861
user3400321 Avatar asked Feb 04 '26 03:02

user3400321


1 Answers

Let it wrap around:

this.style.color = colors[i % colors.length];

The expression i % colors.length yields the remainder after division of both operands and will always be in the range of [0, colors.length). It's also referred to as the modulo operator.

An even neater version can be made:

$('#mainMenu span').css('color', function(index) {
    return colors[index % colors.length];
});

Demo

See also:

  • css(propertyName, function(index,value))
  • What does % do in JavaScript
like image 148
Ja͢ck Avatar answered Feb 05 '26 19:02

Ja͢ck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!