This code I wrote styles the characters of the user input into a rainbow.
function button(){ var name = window.prompt("Insert your name"); var namearray = []; namearray = Array.from(name); let colors = ["red","orange","yellow","green","blue","purple"]; for(i=0; i < namearray.length; i++){ element = document.createElement("p"); elementtext = namearray[i]; element.innerHTML = elementtext; document.getElementById("namediv").appendChild(element); element.style.color = colors[i]; } }
The problem is that it only colors words up to 6 characters. What I thought of was repeating the iteration of the color array in order to color the rest of the input but I don’t know how to apply it.
Advertisement
Answer
Use the %
operator:
element.style.color = colors[i % colors.length];