Loop through the array list to add different color options to each list item, and then

I have a range of vibrant colors that I would like to assign to each list item in my unordered list. However, once the number of list items exceeds the number of colors available, I want the colors to cycle back to the beginning color. Take a look at this example:

http://jsfiddle.net/NjqYA/57/

$(document).ready(function(){
var colors = ['#0098c3', '#bed600', '#a30050', '#9b1889'];
$('#div_id ul li').each(function(i){
    $(this).css('backgroundColor', colors[i % colors.length]);
});});

Thank you in advance!

Answer №1

Utilize the modulo operator to create a looping effect.

$(document).ready(function(){
    var colors=['#00ffcc','#ffcc00','#9900ff','#ff0099'];
    $('#element_id ul li').each(function(i){
        $(this).css('backgroundColor',colors[i % colors.length]);
    });
});

Preview

Answer №2

To achieve this, you can utilize the modulus function.

First, set up a counter c. Then, use the expression c++ % color.length as an index. This will ensure that each time the counter exceeds the length of color, it loops 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>

Answer №3

Check out the updated solution, which now incorporates modulus to calculate the remainder:

$(document).ready(function(){
  var colors=['#0098c3','#bed600','#a30050','#9b1889'];
  $('#div_id ul li').each(function(index){
      var colorIndex = index % colors.length;
      $(this).css('backgroundColor',colors[colorIndex]);
  });
});

Answer №4

To achieve alternating background colors for each list item, insert the line i = i % color.length before setting the css background-color property in the jQuery script.

$(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>

Answer №5

Here is a simple solution for you to try:

$(document).ready(function(){
var colors=['#0098c3','#bed600','#a30050','#9b1889'];
$('#container ul li').each(function(i){
        i=i % colors.length;
        $(this).css('backgroundColor',colors[i]);
});
});

If the index i exceeds the length of the color array, it will reset to zero; view the live DEMO here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering relative URLs within an MVC 4 framework

Seeking a solution for storing the fully qualified URL of a relative path in MVC: ~/Content/themes/base/jquery-ui.min.css" In my scenario, I have a hidden input field: <input type="hidden" id="siteUrl" value=""/> I attempted to populate this hidd ...

How can I easily change the background image using Angular 4?

I am currently using inline styles to set the background image on my website. <div [ngStyle]="{background: 'url(' + section.backgroundSrc + ') no-repeat'}"> But I want to find a cleaner solution, perhaps dynamically setting the ...

JavaScript validation for a form dynamically generated within a table

NOTE: Utilizing Foundation 6 along with the Abide Form Validation. I'm currently working on implementing automatic form validation for a website. The approach I've taken involves creating a table (using the jQuery Datatables library) with multip ...

The console encountered an issue trying to parse the specified value "NaN", which may be out of range or unable to be parsed

I have a project in progress that involves building an exchange platform. I am looking to utilize jQuery/JavaScript to extract data from a select option and then transmit the value to an API URL. However, whenever I run my code, I encounter an issue where ...

Update the text color of user-input content in an input field using Material Design Lite in HTML

When designing an application, I've chosen to have a black background for one of the pages. However, when users type in the input box, their text ends up being black as well, making it invisible. <head> <link rel="s ...

Dragging the close icon of the DIV along with the DIV

Check out the JSFiddle I'm having trouble getting the close icon within a draggable DIV to move along with the rest of the DIV. It seems like there might be an issue in this part of the code. $self = $(this); $(opts.parent).append($self); $('sp ...

Having trouble with JS functionality in ASP.NET?

While experimenting, I discovered a way to update the text of both label and textbox when a checkbox is clicked. It appears that asp.net provides extensive support for JavaScript. <script type="text/javascript> $(document).ready(function () { ...

What steps can be taken to ensure the visibility and accessibility of two vertically stacked/overlapped Html input elements in HTML?

I have encountered a challenge with my HTML input elements. There are two input elements that overlap each other, and I would like to make both inputs visible while only allowing the top input to be editable. I have tried several approaches involving z-ind ...

Show a div once all its content has been fully loaded

I have a section on my webpage that includes images, text, and links. It functions as a carousel. My goal is to show the section only after all content has loaded. I am looking to transition from opacity 0 to opacity 1 with a fade-in effect. Here is the ...

toggle classes using jQuery when a link is clicked

I'm currently working on a jQuery function that will apply a class to a selected link (which opens a page in an iframe) and then remove that class when another link is chosen. Previously, I received assistance from another member for a similar task in ...

Triggering an action with JQuery when clicking on a button within an Angular

I need to open a new link whenever a column in my datatable is clicked. Below is the code for my datatable which fetches data through an ajax call- <table datatable="" dt-options="dtOptions" dt-columns="dtColumns" class="featuretable row-border compact ...

The functionality of the click and mousedown events seems to be disabled when using an Ajax form

Trying to create a simple Ajax popup featuring a form with 3 data fields and a submit button, however I'm unable to trigger the submit button programmatically. jQuery('#FormSubmit').click() seems to have no effect. The same goes for jQuer ...

What is the best way to ensure that my top menu remains fixed while scrolling?

Link to website: I am looking to have the top menu on my page remain fixed at the top of the screen as users scroll. Does anyone know if this is achievable, and if so, how can I implement it? ...

Updating the background-image using Jquery when a button is clicked

Is there a way to change the background image of a division using a button click without the need for a function? <input onclick="jQuery('#Div1').hide(); jQuery('#Div2').show(); jQuery('#main').css("background-image", "url ...

Exploring the functionality of arrays in PHP

As I delve into my inaugural PHP program, a fundamental query has arisen. My task is to output a string stored within an array. Within my code, there exist two arrays: $content and $type. The former contains a numeric value at position $content[$i][15] ( ...

Activate an event on a separate webpage using jQuery or JavaScript

Currently, I am in the process of working on a project with 2 distinct pages: Index Settings On the Settings page, I have implemented a button to close an element and hide it. However, I am encountering an issue where I want the elements on the Index pa ...

The issue arises when attempting to upload a file through an ajax submission that returns false

I am working on a form that includes a simple file input field. <form id="uploadFile" name="uploadFile" action="addFile.php" method="POST" enctype="multipart/form-data"> <input type="hidden" value="" name="uploadWUID" id="uploadWUID"> ...

Utilize the power of modern Javascript to extract and display data from a JSON file by mapping an array and adding it

I've been attempting to construct a table from a JSON file by utilizing the map method in React. I've experimented with two approaches - one using map and the other using a for loop - but so far, I haven't been successful in getting the desi ...

AngularJS static list with dynamically changing content

Seeking inspiration on creating an AngularJS information monitor with a maximum of 6 rows. The display should show new rows at the top, pushing out the oldest row from the bottom when there are already 6 rows visible. Rows can also disappear unexpectedly. ...