Hexadecimal colour values
This example demonstrates how Javascript can convert between hexadecimal and decimal numbers by prefixing a (hexadecimal) number with 0x. When a hexadecimal number is parsed, it outputs is decimal equivalent.
This little trick avoids having to write a function to do the conversion.
Understanding hexadecimal numbers is important because they are used to define the web colors. These can be specified with either a single hexadecimal digit for each of the red, green and blue (RGB) components that make up the color. Alternatively each RGB component may be specified by two hexadecimal digits. In HTML the hexadecimal number is preceeded by a hash (#) symbol.
In this example the values for the RGB colours are to be input as 2 digit hexadecimal numbers. For clarity any error checking has been omitted.
Sample form - illustration only
The HTML code
<form>
<p>enter R <input id="red" type="text" size="2" />
G <input id="green" type="text" size="2" />
B <input id="blue" type="text" size="2" />
<input type="button" value = "go" onclick = "test()" /></p>
<div id="swatch" style="background-color:#000000;
width:300px;height:200px;"></div>
</form>
The Javascript code
function test()
{
var red = document.getElementById('red').value;
var green = document.getElementById('green').value;
var blue = document.getElementById('blue').value;
//concatenate values
var color = red + green + blue;
//since typeof string
alert(typeof(color) + " = " + color);
//prefix string with 0x implies it is a hexadecimal number
//the Hexadecimal and decimal equivalents
var msg = "Hex " + ("0x" + color)
msg += " is decimal " + parseInt("0x" +color));
//change background color of swatch to selected color value
var tst =document.getElementById('swatch');
tst.style.backgroundColor = "#" + color;
alert(msg);
}
| Attachment | Size |
|---|---|
| HexColorValues-Ex1.htm | 1.64 KB |

