How can I use jQuery to automatically change the background color of each item to match the color of the next

I have a list with 4 items, each item has a specific background color set in the style attribute.

<div class="list">
  <div style="background: red"></div>
  <div style="background: blue"></div>
  <div style="background: green"></div>
  <div style="background: yellow"></div>
</div>

I would like to change the background color of each item to the color of the next item in the list. The HTML code above should be changed to:

<div class="list">
  <div style="background: yellow"></div>
  <div style="background: red"></div>
  <div style="background: blue"></div>
  <div style="background: green"></div>  
</div>

I have tried implementing this code, but it is not working.

$(".list > div").each(function(i){
  var index = i == 0 ? 3 : i-1;
  this.style.background = $(".list > div").eq(index)[0].style.background;
});

The current code sets the color of the last item to all items. What could be the issue?

setInterval(function(){  
  $(".list > div").each(function(i){
    var index = i == 0 ? 3 : i-1;
    this.style.background = $(".list > div").eq(index)[0].style.background;    
  });
}, 1000);
.list > div { height: 50px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list">
  <div style="background: red"></div>
  <div style="background: blue"></div>
  <div style="background: green"></div>
  <div style="background: yellow"></div>
</div>

Answer №1

The issue with the code is that in the JavaScript function .each(), it sets the color of the last item to the color of the first item and then propagates this color change to the rest of the items. Below is an example of the loop:

  • Item1: changed to the color of item4, which is yellow
  • Item2: changed to the color of item1, which is yellow
  • Item3: changed to the color of item2, which is yellow
  • Item4: changed to the color of item3, which is yellow

As a result, all items end up being changed to the color yellow.

The solution is to store the colors of the items before making any changes, and then apply the color change to each item using the previously stored colors.

setInterval(function(){  
  var colors = $(".list > div").map(function(){
    return this.style.background;
  }).get();
  $(".list > div").each(function(i){    
    var index = i == 0 ? 3 : i-1;
    this.style.background = colors[index];
  });
}, 1000);
.list > div { height: 50px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list">
  <div style="background: red"></div>
  <div style="background: blue"></div>
  <div style="background: green"></div>
  <div style="background: yellow"></div>
</div>

Answer №2

In my opinion, this approach is superior (mainly because the exact count of child-elements is not essential).

Simply take the final element in the array and reposition it as the initial one. Next, assign colors to each child-element individually.

setInterval(function(){  
  var colors = $(".list div").map(function(){
    return this.style.background;
  }).get();
  colors.unshift(colors.pop())
  
  $(".list div").each(function(i){    
    this.style.background = colors[i];
  });
}, 1000);
.list > div { height: 50px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list">
  <div style="background: red"></div>
  <div style="background: blue"></div>
  <div style="background: green"></div>
  <div style="background: yellow"></div>
</div>

Answer №3

Although you've already shared your own solution, I wanted to provide a slightly different approach using plain JavaScript (specifically ES6) to achieve the same outcome:

// This anonymous function runs continuously with a set interval in milliseconds:
setInterval(function() {

  // Gathering the necessary elements and converting the result into an array:
  let children = Array.from(document.querySelectorAll('.list > div')),
    // Creating an array of background-colors of the found elements:
    colors = children.map(
      // Utilizing an arrow function to retrieve the background-color of each element:
      child => window.getComputedStyle(child, null).backgroundColor
    );

  // Iterating over the children array using forEach():
  children.forEach(function(child, index, array) {
    // Setting the background-color of each element based on the calculated index:
    child.style.backgroundColor = colors[
      // Applying a formula using index and array length to determine the new color:
      (index + 1) % array.length
    ];
  });
}, 1000);

setInterval(function() {
  let children = Array.from(document.querySelectorAll('.list > div')),
    colors = children.map(child => window.getComputedStyle(child, null).backgroundColor);

  children.forEach(function(child, index, array) {
    child.style.backgroundColor = colors[(index + 1) % array.length];
  });
}, 1000);
.list > div {
  height: 50px;
  font-size: 2em;
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list">
  <div style="background: red">One</div>
  <div style="background: blue">Two</div>
  <div style="background: green">Three</div>
  <div style="background: yellow">Four</div>
</div>

References:

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

Avoiding duplication of prints in EJS template files

In my EJS code, I have created a loop to fetch the total amount of items from the database. Here is my current code: <h2>Summary</h2> <% if(typeof items.cart!=="undefined"){ var amount = 0; %> <% i ...

Arrange the array based on the order of the enumeration rather than its values

Looking to create an Array of objects with enum properties. export enum MyEnum { FIXTERM1W = 'FIXTERM_1W', FIXTERM2W = 'FIXTERM_2W', FIXTERM1M = 'FIXTERM_1M', FIXTERM2M = 'FIXTERM_2M', FIXTERM3M = 'FIX ...

jQuery function to alternate between appearing and disappearing captions every 5 seconds

I have a unique project that requires my image captions to both appear and disappear every X seconds. While I have successfully achieved this effect once, I need the captions to continuously "loop". Here is the code I am currently using: <figure> ...

Tips on passing a variable into a controller using jQuery AJAX from the URL

Can you help me figure out how to pass an id to a function in the controller? I keep getting an error saying it cannot find the method in the controller. Here's my view: function Delete1(id) { if (confirm("Are you sure?")) { $. ...

I am experiencing an issue where my Laravel website does not refresh automatically

Having trouble with the URL (url: "/ultimo-pedidox"). It seems to be loading correctly, but the view isn't refreshing as expected. @extends('store/template') @section('content') <div style="margin-top: 55px;" ...

Displaying a loading animation to keep users engaged while AJAX calls retrieve data from the server

My issue was outlined in a recent discussion on Stack Overflow. In essence, my goal is to display a loading indicator before server-side processes complete: [Loader] -> [Target page]. However, the HTML content loads after the server-side tasks, resultin ...

Instructions on how to present a list of employee information according to the user's gender preference using a selection of three radio buttons

I have developed a view that displays a table of employees, using a json array to store their details in the component. Additionally, I have implemented 3 radio buttons: all, male, and female. My goal is to have the table show all employees when "all" is ...

Revamp the sequence of divs using jQuery

<div class="example first">111</div> <div class="example second">222</div> <div class="example third">333</div> Can the order of these divs be changed using jQuery? I am looking to get: <div class="example second"&g ...

Tips for getting a browser to clear the cache specifically for the .html files on your website

After making updates to a client's website, I'm encountering an issue where the browser is displaying a cached version of the site. The website consists of static .html files. Although clearing my browser's cache resolves the issue for me, I ...

What steps can I take to add a horizontal scroll bar and view the entirety of my image?

<img src="the fake.png" width="3268" height="538" class="table" alt=""/> I have a large image that is getting cut off on the page. I need to add a horizontal scrollbar so I can view the entire image ...

Creating a Commitment - Resolving the "Expected ')' after argument list" Error

Can someone please help me locate the syntax error in this code snippet? I've been searching for ages! An error occurred: Uncaught SyntaxError: missing ) after argument list promiseArray.push( new Promise(function (resolve, reject) { ...

The controller in Rails3 is not receiving the parameters properly when using coffeescript and ajax

Currently, I am working on setting up a sorting list using Rails3 and coffeescript. Earlier, I encountered a routing problem which I was able to resolve with the kind assistance from someone. However, I now face a different issue where my data parameter is ...

Using jQuery validation to verify that a minimum of one radio button holds a true value

I have a form with two questions. The first question asks if the product value exceeds a certain fixed amount, and the second question asks if the product value is below that fixed amount. Upon submitting the form, validation should ensure that at least on ...

Can SVG use a transformation matrix to switch the values of x and y coordinates?

Currently using the svgpath library to manipulate SVGs, I am looking for a way to alter the coordinate system so that the y-axis becomes the x-axis and the x-axis becomes the y-axis. Is there any method to achieve this? I have attempted to rotate around ...

Utilizing Jquery to extract a specific string from a URL and fetch a remote element

Recently delving into Jquery, I'm in search of a code snippet that can capture the current page URL and load a remote element if it contains a specific string. For instance: Consider these sample page URLs: "http://......./Country/AU/result-search- ...

Struggling to extract information from HTML code through Python web scraping techniques

Hello there! I'm currently in the process of extracting dividend history data for a specific stock from a website using web scraping in Python. However, being new to Python, I'm facing some challenges in retrieving the data. Below is a snippet of ...

Expanding Images for Optimal Display in Responsive Design

I have a collection of large images in various sizes that I need to display without any stretching inside a container with set height. The challenge is to make the image fit perfectly within the container without distorting its proportions. I must achieve ...

Having issues with handling button click events in jQuery

I'm currently working with jQuery to show a div when a button is clicked, but for some reason, it's not functioning as expected... HTML: <input type="button" id="addmoresg" value="Add More" name="button"> <div id="addsg" style="display ...

Having trouble with the page redirection issue? Here's how you can troubleshoot and resolve

My goal is to restrict access to both the user home and admin dashboard, allowing access only when logged in. Otherwise, I want to redirect users to the login or admin login page. import { NextResponse } from 'next/server' import { NextRequest } ...

Issue with undefined bindingContext.$data in IE9 on knockout binding handler

I'm attempting to create a unique binding handler that applies role-based access to fields on a page. This custom handler uses the values of other observables from the viewModel to enable or disable input controls based on certain conditions. However ...