Changing the styles dynamically in a web page


This example explains changing the fore color of text in an element/tag.

Let us create an html web page and add a span tag by with id as Time.

Now write a JavaScript function like as follows in <head> tag.


<script>

var hexvalues = Array( "A", "B", "C", "D", "E", "F", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" );

function updateTime()
{
    var colour = '#';
    for( var counter = 1; counter <= 6; counter ++ )
    {
        var hexvalue = hexvalues[ Math.floor( hexvalues.length * Math.random() ) ];
        colour = colour + hexvalue;
    }
   
    var Chtime = document.getElementById('Time');
    if(Chtime)
    {
        var dt=new Date();
        Chtime.innerHTML=dt.toLocaleString();
        Chtime.style.color=colour;
    }

    //for changing webpage back ground color
    //document.bgColor=color;
 

}
    updateTime();
    window.setInterval(updateTime, 1000);

</script>


The above function updateTime() is called for every second, and the fore color of text in span tag will change randomely.

To call the function for specified time interval we use window.setInterval(function_name, time_interval).

For randomization fortunately there is a function in javascript called Math.Random().