Reputation: 77
i have a list of colors that i want to add to a each li in my ul, but after the number of li's passes the number of colors i would like the colors to start from the first color. Here's what i mean
$(document).ready(function(){
var color=['#0098c3','#bed600','#a30050','#9b1889'];
$('#div_id ul li').each(function(i){
$(this).css('backgroundColor',color[i]);
});});
thank you in advanced
Upvotes: 2
Views: 872
Reputation: 32145
Well just try the following:
$(document).ready(function(){
var color=['#0098c3','#bed600','#a30050','#9b1889'];
$('#div_id ul li').each(function(i){
i=i % color.length;
$(this).css('backgroundColor',color[i]);
});
});
If i
reaches color.length
then initialise it; here's the working DEMO.
Upvotes: 0
Reputation: 2404
Just add i = i % color.length
before the css background-color
$(document).ready(function() {
var color = ['#0098c3', '#bed600', '#a30050', '#9b1889'];
$('#div_id ul li').each(function(i) {
i = i % color.length
$(this).css('backgroundColor', color[i]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div_id">
<ul>
<li><a href="#">stupid link 1</a>
</li>
<li><a href="#">stupid link 2</a>
</li>
<li><a href="#">stupid link 3</a>
</li>
<li><a href="#">stupid link 4</a>
</li>
<li><a href="#">stupid link 5</a>
</li>
<li><a href="#">stupid link 6</a>
</li>
<li><a href="#">stupid link 7</a>
</li>
<li><a href="#">stupid link 8</a>
</li>
</ul>
</div>
Upvotes: 0
Reputation: 7753
Here is the corrected version, using modulus to get the remainder:
$(document).ready(function(){
var color=['#0098c3','#bed600','#a30050','#9b1889'];
$('#div_id ul li').each(function(i){
var colorIndex = i % color.length;
$(this).css('backgroundColor',color[colorIndex]);
});
});
Upvotes: 1
Reputation: 780889
Use the modulus operator to loop around.
$(document).ready(function(){
var color=['#0098c3','#bed600','#a30050','#9b1889'];
$('#div_id ul li').each(function(i){
$(this).css('backgroundColor',color[i % color.length]);
});
});
Upvotes: 3
Reputation: 22992
You could use modulus to do this.
Initialize a counter c
, use c++ % color.length
as a index so everytime it gets above the length of color
it jumps back to 0
.
$(document).ready(function() {
var color = ['#0098c3', '#bed600', '#a30050', '#9b1889'];
var c = 0;
$('#div_id ul li').each(function(i) {
$(this).css('backgroundColor', color[c++ % color.length]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div_id">
<ul>
<li><a href="#">stupid link 1</a>
</li>
<li><a href="#">stupid link 2</a>
</li>
<li><a href="#">stupid link 3</a>
</li>
<li><a href="#">stupid link 4</a>
</li>
<li><a href="#">stupid link 5</a>
</li>
<li><a href="#">stupid link 6</a>
</li>
<li><a href="#">stupid link 7</a>
</li>
<li><a href="#">stupid link 8</a>
</li>
</ul>
</div>
Upvotes: 1