0

i want to change font color for part of text every second using react and javascript.

this is my string "good morning"

i want the text "morning" to change colors

below are the colors i want to change

red, green, blue, yellow, purple, pink, black

below is what i have tried,

const Parent = () => {
    <div>
        <span>good</span>
        <span class="change">morning</span>
    </div>
}


.change {
    animation: change 1s step-end both;
}

@key-frames change {
    from {color: red}
    to {color: green}
}

but the above only changes the text from red to green. how do i keep it as a loop like should change text color from red, green, blue, yellow, purple, pink, black and again red,green and so on.

could someone help me fix this. thanks.

  • Have you seen this answer? https://stackoverflow.com/a/16782559/5605822 – Tasos Sep 28 '20 at 11:39
  • Does this answer your question? [Looping Animation of text color change using CSS3](https://stackoverflow.com/questions/16782498/looping-animation-of-text-color-change-using-css3) – Tasos Sep 28 '20 at 11:40

1 Answers1

0

Fix your syntax (@key-frames -> @keyframes), make the animation infinite and add more color steps:

.change {
  animation: change 1s step-end infinite;
}

@keyframes change {
  0% {
    color: red
  }
  25% {
    color: green
  }
  50% {
    color: orange
  }
  75% {
    color: blue
  }
}
<div>
  <span>good</span>
  <span class="change">morning</span>
</div>

If you are planning on using this with React, you'll also need className="change" instead of class="change".

AKX
  • 152,115
  • 15
  • 115
  • 172
  • thanks so to add yellow, pink, purple, black colors should i do something like 100% {color: yellow} 125% {color: pink} 150% {color: purple} 175% {color: black}? – stackoverflow_user Sep 28 '20 at 11:44
  • No, the % must remain between 0 and 100. If you have 8 total colors, you'll need 0% 12.5%, 25.0%, 37.5%, 50.0%, 62.5%, 75.0%, 87.5%. – AKX Sep 28 '20 at 11:48