Looking to update the background color of a div every 3 seconds?

Every 3 seconds, I need to change the background color of each div. To do this, I attempted to modify the values in the color array every 3 seconds. For example, the value at index 0 (which is "red") would move to index 1, then the value at index 1 would move to index 2, and so on. Finally, the value at index 4 would always be set to index 0's value. The issue is that I couldn't achieve this new edited array. How can I properly edit the color array values with each call?

<style type="text/css">
 div {
    width: 100%;
    height: 20%;
    position: relative;
    background: #fff;
     }
</style>
<body>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>

 <script>
       var div = document.getElementsByTagName("div");
       var color = ["red","green","pink","blue","lightblue"];
       function change(){
          for(var i in color){
             var j = parseInt(i);
             j !== 4 ? color[j+1].Key = color[j] : color[0].Key = color[j];
          }
       changediv();
      }
      function changediv () {
        for(var d = 0 ; d < div.length; d ++){
                 div[d].style.background = color[d];
            }
        
      }

     setInterval(change,3000);
</script>

Answer №1

This could prove to be very useful.

var divs = document.getElementsByTagName("div");
var color = ["red","green","pink","blue","lightblue"];
var colorIndex = 0;
var divIndex  = 0;

function change (){
   for(var i = 0 ; i < divs.length; i ++){
                 divs[divIndex].style.background = color[colorIndex];
                  colorIndex++;
                  colorIndex = (colorIndex == color.length?0:colorIndex);
                  divIndex++;
                  divIndex = (divIndex == divs.length?0:divIndex); 
            }  
          divIndex++;
          divIndex = (divIndex == divs.length?0:divIndex); 
}

setInterval(change,1000);
div{
  height:50px;
  width:50px;
}

span {
  display: flex;
}
 <span>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 </span>

And here is a Functional Jsfiddle link

Answer №2

My solution may not be the most elegant, but it gets the job done and I have made sure to break it down step by step for easier understanding.

OP: could you also clarify why using a for-in loop results in an additional value?

I've come across information stating that the use of `for in` loops is more suitable for iterating through objects rather than arrays because there is no guarantee of the order of results. Therefore, if you use a `for in` loop to iterate over an array, chances are the elements will be returned in a different order, essentially treating the array like an object with less focus on its indexed structure.

The reason for the extra value when using `for in` lies in the fact that it interprets the array not only as its contents (`0,1,2,3,4`) but also enumerates properties such as `length`, `item`, and `callItem`. These extra unnecessary elements can complicate things unnecessarily. In this scenario, the div behaves more like a NodeList; had it been an array, even more properties would have cluttered the list.

Plunker

Snippet

<!DOCTYPE html>
<html>

  <head>
 <style>
 div {
   width: 100%;
   height: 20vh;
   border: 1px solid #fff;
   background: #555;
 }
 </style>
  </head>

  <body>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    
    <script>
      //Declare color Array
      var color = ["red","green","pink","blue","lightblue"]; 
      
    //Function takes one argument
    function fill(color) {
      
      //Collect all divs and make a NodeList
      var divList = document.querySelectorAll('div');
      
      //Make the NodeList an Array
      var divArray = Array.prototype.slice.call(divList);
        
        //Iterate through divArray
        for(var i = 0; i < divArray.length; i++) {
          
          //Each iteration of divArray is matched to an element of color
          var div = divArray[i];
          var bg = color[i];
          
          //Set each background of div to the corresponding color in color Array
          div.style.backgroundColor = bg;
        }
      }
    

    setInterval(function() {

      
        //Call fill with the given Array color
        fill(color);
        
        //x is the last element of color Array
        var x = color[4];
      
        //Remove x from the back of color Array 
        color.pop(x);
      
        //Place x to the front of color Array 
        color.unshift(x);
      
      //Do it again in 3 seconds
    }, 3000);  
  </script>
</body>

</html>

Answer №3

While the for-in statement itself is not inherently problematic, it can be misapplied in certain situations, such as when iterating over arrays or array-like objects.

The primary purpose of the for-in statement is to list object properties. This statement will traverse up the prototype chain, including inherited properties, which may not always be desired.

Reference:

It is recommended to use for index instead.

Answer №4

If you're looking to modify the color of all div elements in a specific array, this code snippet can achieve that.

Here's a possible solution:

var divElements = document.getElementsByTagName("div");
var colors = ["purple","orange","teal","yellow","lightgreen"];
var currentIndex = 0;

function changeColors (){
   for(var i = 0; i < divElements.length; i++){
                divElements[i].style.background = colors[currentIndex];
            }
    currentIndex++;
    currentIndex = currentIndex === colors.length ? 0 : currentIndex;
}

setInterval(changeColors,3000);

Answer №5

div {
    width: 100%;
    height: 20%;
    position: relative;
    background: #fff;
    animation:myfirst 12s;
   -moz-animation:myfirst 12s infinite; /* Firefox */
   -webkit-animation:myfirst 12s infinite; /* Safari and Chrome */
  }


  @-moz-keyframes myfirst /* Firefox */
{
0%   {background:red;}
25%  {background:green;}
50%   {background:pink;}
75%  {background:blue;}
100%  {background:lightblue;}
}
 
    @-webkit-keyframes myfirst /* Firefox */
{
0%   {background:red;}
25%  {background:green;}
50%  {background:pink;}
75%  {background:blue;}
100%  {background:lightblue;}
}
  
 <div>1</div>
 <div>2</div>
 <div>3</div>
 <div>4</div>
 <div>5</div>

Answer №6

For this specific task, JavaScript isn't necessary:

div {
  animation: cycle-colors 15s steps(1, end);
  -moz-animation: cycle-colors 15s steps(1, end) infinite;
  -webkit-animation: cycle-colors 15s steps(1, end) infinite;
}
@-moz-keyframes cycle-colors {
  0% {
    background: red;
  }
  20% {
    background: green;
  }
  40% {
    background: pink;
  }
  60% {
    background: blue;
  }
  80% {
    background: lightblue;
  }
}
@-webkit-keyframes cycle-colors {
  0% {
    background: red;
  }
  20% {
    background: green;
  }
  40% {
    background: pink;
  }
  60% {
    background: blue;
  }
  80% {
    background: lightblue;
  }
}
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>

If you employ a pre-processor like Sass, you can add more programmability to it:

$colors: (
  red,
  green,
  pink,
  blue,
  lightblue
);
$colors-length: length($colors);
$frame-duration: 3s;
$animation-duration: $frame-duration * $colors-length;

div {
  animation:cycle-colors $animation-duration steps(1, end);
 -moz-animation:cycle-colors $animation-duration steps(1, end) infinite;
 -webkit-animation:cycle-colors $animation-duration steps(1, end) infinite;
}


@-moz-keyframes cycle-colors {
  @for $i from 1 through $colors-length {
    $stop: 100 / $colors-length * ($i - 1) + 0%;
    #{$stop} { background: nth($colors, $i)};
  }
}

@-webkit-keyframes cycle-colors { 
  @for $i from 1 through $colors-length {
    $stop: 100 / $colors-length * ($i - 1) + 0%;
    #{$stop} { background: nth($colors, $i)};
  }
}

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

I am unable to access the information from my api link using ajax

Before fetching data from my link (), I tested it in my browser and it worked fine. It returned JSON format, but I encountered an error when trying to access the same link with AJAX. Thank you, Below is the code snippet: <script type="text/javascript ...

Issue with jqLite's .triggerHandler() functionality not behaving as anticipated

I'm having an issue with a piece of code that uses triggerHandler. The event is being called correctly, but it's not working as expected. Below is the code snippet and a link to a jsFiddle : HTML: <body ng-app="app"> <button box-cr ...

Don't forget the last click you made

Looking for a way to style a link differently after it has been clicked and the user navigates away from the page? Check out this code snippet I've been using: $(document).ready(function(){ var url = document.URL; function contains(search, find) { ...

Align the text to the center within the Paper component using React and Material-ui

I've been struggling to center text inside a paper component in Material UI, and nothing seems to be working. I attempted using display:flex in the parent component with align-items:center in the child component. I also tried adding padding:5px for eq ...

Create a resizable textarea within a flexbox container that allows for scrolling

Hey there! I'm struggling with a Flexbox Container that has three children. The first child contains a textarea, but it's overflowing beyond its parent element. Additionally, I want to make the content within child 2 and 3 scrollable. I've ...

Effective strategies for managing form submissions with React and Typescript

As I dive into refactoring my code to TypeScript, especially as I am still getting accustomed to it, I find myself pondering about the HTML element types with React events. This has led me to rethink how I approach form creation and submission event handli ...

Checkbox customization that shifts position when clicked

I seem to be missing something as I can't seem to find a solution for this particular issue. I have implemented custom checkboxes on a list of sentences. Initially, they appear fine, but once you check the first checkbox, it shifts its position. I am ...

tips for exporting database information to an excel file with the help of ajax request and javascript

Recently, I built an application using NDWS with sapui5 _javascript. Within the application, there is a table that contains data synced with the server's database. My goal is to retrieve this data from the table and export it to an Excel document. Her ...

IE11 Experiencing Overflow Issue with List Item Pseudo Element Numbers

Having a simple unordered list of links and using pseudo elements to generate numbers for the list, I encountered an issue with centering the number vertically within its circle background in Internet Explorer 11. Here is the HTML code: <ul> < ...

HTML various button designs - such as a cogwheel

I need a button on my Angular/Electron project that resembles a gear icon. I came across these resources: here and here. However, when I tried to implement them, they didn't work as expected. Currently, the button looks like this: <button class= ...

Is it possible to continuously generate webpages using AJAX?

Is there a way to achieve an infinite scrolling effect in all directions using ajax requests without the need for flash or silverlight? If anyone has an example of this, I would love to see it! Thank you for your time. ...

Error: Koa.js framework is unable to find the "users" relation in the Sequelize database

I am currently facing an issue while attempting to establish a relationship between two tables, 'user' and 'accessToken'. The error message I am encountering is hindering the process. Below are the models in question:- User model:- ...

producing imperfections on tiny items

I am currently working on rendering a texture onto a cylinder using threeJS. While it usually works well, I have encountered some strange artifacts when the radius of the cylinder is set to very low values (such as 0.0012561892224928503 in the image attac ...

Ending the Overlay

I am using an overlay: <div id="overlayer" class="overlayer"> <div id="board" class="board"></div> </div> Here are the CSS properties I have applied to it: #overlayer { position:fixed; display:none; top:0; left:0; width:100%; hei ...

Add new data to an existing array in Angular 7 without overwriting it

After clicking a button, I'm retrieving data from the WordPress API: <a (click)="initGetComments()">Get comments</a> This is the code snippet: export class AppComponent { commentsResults: CommentsItem[] = []; ...

Gliding along a div and concealing it out of view, making it seem like it has disappeared

I attempted to slide down the ".preloader" div after a 2-second delay using JQUERY, but I couldn't get it to work as expected. I didn't want to use a toggle button for this effect. I also experimented with creating an animation using @keyframes, ...

Service Worker's fetch event is not triggered upon registering the service worker

Service Worker is a new concept to me. As I delved into learning how to incorporate Service Worker into My Next.js Application, I encountered an issue with the fetch event handler. Oddly enough, the fetch event handler doesn't trigger upon initially r ...

Learn how to establish a state using an array and effectively utilize the setState() method in React

For my latest project, which is API based, I am working with arrays that contain sub-arrays. How can I define a state with an array and utilize the setState() method to work with the entire array? ...

Switching Next.js route using pure JavaScript

Currently, I am facing a challenge in changing the route of a Next.js application using vanilla Javascript. In order for the code to be compatible with Chrome Dev Tools, I cannot dynamically change the route with Next.js and instead must find a solution us ...

Revitalizing HTML and Google Maps with AJAX, PHP, and JQuery

Context: I am currently working on a project that involves integrating a Simple Google Map with an HTML form right below it. The form collects user input and upon submission, sends the data via AJAX to a PHP script for processing API calls and generating i ...