Step 4 - Continuing the JavaScript code

Changing the background color

The original web page used the actual time as background color values. I do not want to do it exactly the same way. First I want to use the whole RGB range from 0 to 255. Second I'm converting these values to hexadecimal values. To get the whole RGB range instead of hours (24) and minutes respective seconds (60), we need to get the current time multiplied with 256 divided by 24 or 60. To do this we will use the Math object which allows us to perform mathematical tasks on numbers, in this case we will use round. We add the following in the dotime() function.

// Use the entire range
var rgbHour = Math.round(hours*(256/24));
var rgbMinute = Math.round(minutes*(256/60));
var rgbSecond = Math.round(seconds*(256/60);

Then the RGB values need to be translated to hexadecimal values. We do that by calling a function componentToHex and attaching value for hour, minute, and second respectively. We store the returned hex value in a new variable.

// Change from RGB to hex values
var hourHexDec = componentToHex(rgbHour);
var minuteHexDec = componentToHex(rgbMinute);
var secondHexDec = componentToHex(rgbSecond);

We write a new function in the same js-document as the dotime() function, just leave an empty line or two and then write the new function below. The function componentToHex(c) receives the time value and stores it in the variable c. Then the time value is converted to a string with the hexadecimal value. Then we check if the string length is equal to 1, if so a 0 is added in the beginning of the string. Then the string is returned to dotime().

function componentToHex(c) {
// Convert number in c to string with hexadecimal value
var hex = c.toString(16);
// If string length = 1 add a 0, return string
return hex.length == 1 ? "0" + hex : hex;
}

When all time values have been changed into strings with the hexadecimal value and returned to the dotime() function, these strings are combined to a string used to change the background color in HTML in the dotime() function.

// Make string for HTML
var hex = "#" + hourHexDec + minuteHexDec + secondHexDec;

// Update the body background color
document.body.style.background = hex;