Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change text color after X amount of seconds?

this is my code:

<font color=green>
     14:00
</font><br>
<font color=green>
     14:30
</font><br>
<font color=green>
     15:00
</font><br>
........

How can I change color (in red) of every single text after some time has passed?

I have tried this code but obviously it doesn't function (onLoad is only for the body/img tags):

<font color=green onLoad="setTimeout('this.style.color=red',xxx-seconds);">
     14:00
</font><br>

Any suggestions?

Solution adopted (thanks to minitech):

<style>
    @keyframes change {
        from { color: green }
        to   { color: red }
    }
</style>

<span style='animation: change (number-of-seconds)s step-end both;'>
    14:30
</span>
<span style='animation: change (number-of-seconds)s step-end both;'>
    15:00
</span>
.............
like image 799
Ken Avatar asked Jun 26 '13 12:06

Ken


2 Answers

You could use CSS animations for this:

font {
    animation: change 3s step-end both;
}

@keyframes change {
    from { color: green }
    to   { color: red }
}

Live demo: http://jsfiddle.net/simevidas/7ZrtQ/

In the above code, the delay is defined by 3s which represents 3 seconds.

Btw, if you don't want to have the timer execute on page load, but instead want to have it triggered by some subsequent event (e.g. a user click), you can define the animation in a CSS class, and then just add that class to the element later with JavaScript to trigger the effect.

Live demo: http://jsfiddle.net/simevidas/7ZrtQ/3/

enter image description here

like image 156
Šime Vidas Avatar answered Sep 30 '22 20:09

Šime Vidas


Something like this:

setTimeout(function(){
    document.getElementsByTagName("p")[0].style.color = "#cccccc";
},3000);

Because getElementsByTagName returns an array of <p> elements, we want to select the first one, with [0], because the array count starts from 0.

You might need to change the getElementsByTagName part to a <span> tag. Alternatively, there's getElementById.

getElementsByClassName

Alternatively,if you want to target each element with the same class, you can do:

function targetGroup(className){
    // loop throgh the elements
    var elemArray = document.getElementsByClassName(className);
    for(var i = 0; i < elemArray.length; i++){
        elemArray[i].style.color = "#ffff00";
    }
}

setTimeout(function(){
    targetGroup('foo'); // this is the class name you are targetting.
},2000);

And your HTML would look like:

<span class="foo">bar</span>
<span class="foo">bar</span>
<span class="foo">bar</span>
<span class="foo">bar</span>
<span class="foo">bar</span>
<span class="foo">bar</span>

Code modified from the example on this page : http://www.developphp.com/view_lesson.php?v=881

like image 40
Nick R Avatar answered Sep 30 '22 21:09

Nick R