Quick Color Picker

This morning, while trying to make some figures using InkScape, I realized that I did not have a firm grasp on how hexadecimal color codes worked. I decided to fix this by creating a simple JavaScript application to pick out a color, see a <div> with that color, and then display the code.

My first step was determining what the coding for hexadecimal colors is. As it turns out, the hexadecimal encoding is just a base-16 encoding of the standard RGB colors from 0-255. In order to get to base 16, the letters A-F are used. The coding then has two places for each color. This is easily implemented in JavaScript using the following steps:

var colorVals = "0123456789ABCDEF";
function setDivColor() {
    var r = document.getElementById("red").value;
    var g = document.getElementById("green").value;
    var b = document.getElementById("blue").value;    
    var r1 = colorVals[Math.floor(r/16)];
    var r2 = colorVals[r-Math.floor(r/16)*16];
    var g1 = colorVals[Math.floor(g/16)];
    var g2 = colorVals[g-Math.floor(g/16)*16];
    var b1 = colorVals[Math.floor(b/16)];
    var b2 = colorVals[b-Math.floor(b/16)*16];
    var curColor = "#"+r1+r2+g1+g2+b1+b2;
}

The remainder of my code was fairly straightforward. I managed to do everything in pure JavaScript, and reused the slider bars from a previous jsfiddle that made bar graphs.

The final code can be found here and below.