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

When I attempt to utilize the API, the JavaScript implementation of a <script src=...> element seems to interfere

Within one of my HTML files, I encountered the following line near the top: <script src="//maps.google.com/maps/api/js?key=apikey"></script> The API key is currently hardcoded in this file, but I would like to use a configuration option store ...

Looking to locate or track duplicate values within a multi-dimensional array?

In a multidimensional array, I am looking to detect and count duplicates. If duplicates are found, an alert should be triggered. Arr =[[2,"sk"],[3,"df"],[7,"uz"],[3,"df"],[7,"gh"]] Suggestions: One way to ...

Alter the color of Material UI Raised Button when it is hovered over

I am trying to change the background color of a raised button on hover in Material UI. I attempted the following, but it did not work. Is there a way to modify the background color in Material UI for a raised button? Example.JS <RaisedButton ...

Issue with Nextjs 13: Unable to locate 'src/app/dashboard/layout.tsx' (deleted optional layout)

Deciding to start a fresh Nextjs 13.4.5 project, I set up an app directory. Within the app directory, I created a new dashboard directory and added page and layout components. Everything seemed to be functioning smoothly with two layout components - one i ...

Cross-origin resource sharing problem arises when JavaScript is loaded asynchronously using script tags created dynamically

By dynamically creating a script as shown below, the JavaScript source is downloaded asynchronously. let newScript = document.createElement('script'); newScript.src = srcUrl; let firstScript = document.getElementsByTagName('script')[0] ...

Unusual characteristics of decision-making

Here is a snippet of my JavaScript code: function getSelectedText(){ if(window.getSelection){ select = window.getSelection().getRangeAt(0); var st_span = select.startContainer.parentNode.getAttribute("id").split("_") ...

Exploring the syntax of typescript when using createContext

Just starting out with typescript and I have some questions. Could someone break down the syntax used in this code snippet for me? What is the significance of having two groups containing signIn, signOut, and user here? Is the first group responsible fo ...

Display the HTML/CSS layout following the JavaScript window.open action

Encountering issues with printing output in an opened window using JavaScript. I'm creating a new document through window.open and including CDN links to Bootstrap files. While everything appears fine in the opened window, when attempting to print (XP ...

Transmit the canvas image and anticipate the AJAX POST response

I need to send canvas content to my API endpoint using ajax and wait for the response before moving on to the next function. Here is my current sending function: function sendPicture(){ var video = document.getElementById('video'); var canvas ...

How to Stop Element Flickering While Hovering in Selenium IE Webdriver

My code is functioning perfectly in Firefox, but when I try it on Internet Explorer, there is flickering. Here is my code: WebElement mouseOver= driver.findElement(By.linkText("abc")); //I'm locating the element by link text. Selenium finds the ...

Error: The function initMap() is not recognized in the Google Maps API

I have been experimenting with the Flickr API and I'm currently working on asynchronously loading images along with their metadata. To accomplish this, I have a script that utilizes three AJAX calls: $(document).ready(function() { var latLon = { ...

Utilizing Fullcalendar Qtip to display information on mouseover rather than utilizing the eventRender

I have a challenge with integrating Qtip to the eventMousever event instead of the eventRender event in fullcalendar. The main reason for this adjustment is due to the server hosting the data being located in another country, resulting in significant late ...

Do you have any tips on incorporating a sinking hover effect to an image or link?

Custom Arrow Icon I Want to Add Animation To I have designed an arrow icon image that functions as a link. It is positioned on top of a background image. When the user hovers over the arrow, I would like to implement a "sink" effect similar to the example ...

Using flexbox auto margin within nested elements: A guide

Is it possible to achieve consistent margins between the heading and list items using flexbox? section { display: flex; background: #eee; } h1 { background: #bbb; } ul { display: flex; flex: 1; list-style-type: none; background: #ccc; ...

JavaScript event in Chrome extension triggers a browser notification and allows for modification using a specific method

I am currently developing a Chrome extension that is designed to take specific actions when system notifications appear, with the main goal being to close them automatically. One example of such a notification is the "Restore pages?" prompt: https://i.sta ...

Discover the method of using jQuery to dynamically calculate a form field's value

I am trying to create a form with two input fields, numerator and denominator. I want to add a third field, total, that will update automatically every time either the numerator or denominator values are changed. The total value is already calculated cor ...

Adding HTML elements to a Vue Tooltip

Does anyone know how to implement a tooltip in Vue for a table cell that has more than 22 characters in its content? I was looking into using the v-tooltip library (https://www.npmjs.com/package/v-tooltip) Setting the tooltip's content with a simple ...

I possess information stored within the array object below, and I aim to transform it into a different array object format

Here is the response I received from my API: let data = [ { date: '2021-04-27', formatted_date: 'Apr 27', location: [ { date: '2021-04-27', formatted_date: 'Apr 27', countr ...

Error: The options object provided for CSS Loader is not valid and does not match the API schema. Please make sure to provide the correct options when

Summary My Nuxt.js project was created using the command yarn create nuxt-app in SPA mode. However, I encountered an error after installing Storybook where running yarn dev resulted in failure to start the demo page. ERROR Failed to compile with 1 errors ...

Implement a jQuery function to interchange images between variables

I am currently working on a project using Wordpress and ACF to develop an interactive image gallery. I have successfully implemented a feature where, upon hovering over an image, it will swap with another image from the database. However, I am facing issue ...