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.


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');
        var dt=new Date();

    //for changing webpage back ground color

    window.setInterval(updateTime, 1000);


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().