I want to make a text change the color of each letter individually, one at a time. For example:
Hello World
The "H" would be the first to become red, then "E", then "L", and so on.
I’ve tried making each letter a span and using jquery and a loop. But it doesn’t work.
$("span").ready(function(){
var letters = $("span").length;
for (let i = 0; i <= letters; i++){
$("span")[i].css("color", "red");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span>H</span>
<span>E</span>
<span>L</span>
<span>L</span>
<span>O</span>
<span>, </span>
<span>W</span>
<span>O</span>
<span>R</span>
<span>L</span>
<span>D</span>
4
Answers
in jquery you have the function
each
that let you loop on all element of a selectorto "wait" between two color change, you can embed the css change in a
setTimeout
link to the index of the each loopYou’re on the right track, but you will need to delay the change of the
color
for a certain moment (say100ms
) so that the effect can be seen. To have a delay, the methodsetTimeout
is used that accepts 2 arguments:100ms
for example).When picking a delay, say
100ms
, we should multiply it with the index of the current letter (currentspan
to be precise) so that the effect can be seen.Here’s a live demo:
You have to use
eq()
function because you can’t use jquery function on a dom element, with eq you return a jquery element.But the better solution is to use the
each
of jquery.