Im trying to make the inner html of a div to change colors. My div looks like this
<div class = 'child'> <span class="color">F</span> <span class="color">u</span> <span class="color">n</span> <span class="color">n</span> <span class="color">y</span> <span class="color"> </span> <span class="color">k</span> <span class="color">l</span> <span class="color">o</span> <span class="color">k</span> </div>
and my javascript looks like this
var value = document.getElementsByClassName("child")[0].innerHTML; bannerArray = value.split(""); var colourArray = [ "rgb(248, 116, 138)", "rgb(248, 125, 145)", "rgb(248, 140, 160)", "rgb(248, 160, 180)", "rgb(248, 175, 195)", "pink", "rgb(248, 195, 215)", "rgb(248, 205, 235)", "rgb(248, 225, 225)", ]; for ( let i = 0; i < colourArray.length; i++) { for ( let j = 0; j < bannerArray.length; j++) { document.getElementsByClassName("color")[j].style.color = colourArray[i]; } }
the result of that code is basically every letter in the banner array gets the first color from the color array, then the second color, until i end up with all the letters being the last color ie rgb(248, 225, 225). What id like is the first color to pass through the first letter, then move to the second letter, then have the first letter take the second color in the color array, then the second color to move to the second letter, then the first letter to take the third color in the array and so on and so forth like marque for lack of a better description, So very sorry for the wall of text.
Advertisement
Answer
Use setTimeout
Get all the children (spans
) of div with the class child
into an array
I suggest using
id
instead. If there is another div with the same classchild
above this div. The first div ends up getting the styles.
const children = document.querySelector(".child").children;
Define a function to apply color to the characters
function applyColors(children, colorArr) { for (let i = 0; i < children.length; i++) { children[i].style.color = colorArr[i]; } }
Write a function to rotate your colors array. Source
function arrayRotate(arr, reverse) { if (reverse) arr.unshift(arr.pop()); else arr.push(arr.shift()); return arr; }
Clone your colors array as a best practice. ( As you keep changing this array in the next step )
const changingColorsArray = [...colourArray];
Change the color of characters every 1s (1000ms) and apply the same to your characters.
Call the function for one time outside setInterval to apply colors on page load.
// apply colors on page load applyColors(children, changingColorsArray); setInterval(() => { // change colors arrayRotate(changingColorsArray, true); // apply colors applyColors(children, changingColorsArray); }, 1000);
Note: You need to add one more color to your colourArray as there are 10 characters including
in the middle
PS: use const or let
over var
Check here for a working demo