1

How can i write the code to dynamically change the colour of a element in html. For Example : if Hello was the label, from first 2 seconds it should change the colour to yellow and then to green and so on with a transition effect.Thank you

3 Answers3

4

animation could do that:

label {
  animation:colorchg 2s infinite;
  color:green
}
@keyframes colorchg {
  50% {
    color:red;
  }
}
<label>color</label>
G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129
1

How about using CSS3 Animations. I took the concept from W3Schools. Check it out

You can add more background colors by dividing the percentages.

label {

    background-color: red;

    -webkit-animation-name: example; /* Safari 4.0 - 8.0 */
    -webkit-animation-duration: 1s; /* Safari 4.0 - 8.0 */
    -webkit-animation-delay: 1s; /* Safari 4.0 - 8.0 */
    animation-name: example;
    animation-duration: 1s;
    animation-delay: 1s;
    animation-iteration-count: infinite;
}

/* Safari 4.0 - 8.0 */
@-webkit-keyframes example {
    0%   {background-color:red; }
    25%  {background-color:yellow; }
    50%  {background-color:blue; }
    75%  {background-color:green; }
    100% {background-color:red; }
}

/* Standard syntax */
@keyframes example {
    0%   {background-color:red; ;}
    25%  {background-color:yellow; }
    50%  {background-color:blue;}
    75%  {background-color:green; }
    100% {background-color:red; }
}
<label>Mylabel</label>
Ali Rasheed
  • 2,765
  • 2
  • 18
  • 31
1

I would recommend doing this in CSS, but if you want a JS solution, you use setInterval() to define the interval and toggle a class that specifies color or just change element.style.color or whatever, and use CSS transition to transition the color change.

var interval = setInterval(function () {
  label.classList.toggle('color');
},2000)
label {
  transition: 2s;
  color: green;
}
.color {
  color: red;
}
<label id="label">text</label>
Michael Coker
  • 52,626
  • 5
  • 64
  • 64