Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jQuery: Start from first value if values are not there

So I have this array in JS

var values = ["rgb(236,221,208)","rgb(146,177,182)","rgb(191,209,223)","rgb(187,237,190)"];

This array has 4 values, and it is used to add background color to some sections

$(".class").each(function(index) {
    var color = values[index];
    $(this).css("background-color", color);
});

Suppose if we have 6 rows to add background color, then in that case
values[4] and values[5] will be undefined

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want to know is there any method in which we can start over the array values once we reach the end? means once we reach the point where values[4] is undefined so instead of it we can continue with values[0] and so on

values[0], values[1], values[2], values[3], values[0], values[1], values[2] ……….

>Solution :

$(".class").each(function(index) {
    var color = values[index % values.length] ;
    $(this).css("background-color", color);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading