SRM color to HTML color
by John Schulz
HTML
<link rel="stylesheet" href="http://files.seancoates.com/ui-lightness/jquery-ui-1.8.2.custom.css">
<div>
<div id="srmslider" style="width: 300px;"></div>
<div style="margin-top: 10px; padding-bottom: 24px">
SRM: <input type="text" size="4" id="srmnum" />
=
<input type="text" size="10" id="srmhtml" disabled="disabled" />
<div id="srmcolour" style="display: inline-block; width: 100px;"> </div>
</div>
</div>
JavaScript
// program flow + behaviors
jQuery(function ($){
$("#srmslider").slider({
value: 1,
min: 1,
max: 40,
step: 0.1,
slide: function (event, ui)
{
setHtml(ui.value);
}
});
$("#srmnum").bind('change keyup', srmChanged);
setHtml(1);
});
// Util + page functions
function srm2hex( srm )
{
var r,g,b;
if (srm <= 0.1) { // It's water
r = 197;
g = 232;
b = 248;
} else if (srm <= 2) {
r = 250;
g = 250;
b = 60;
} else if (srm <= 12) {
r = (250 - (6 * (srm - 2)));
g = (250 - (13.5 * (srm - 2)));
b = (60 - (0.3 * (srm - 2)));
} else if (srm <= 22) {
r = (192 - (12 * (srm - 12)));
g = (114 - (7.5 * (srm - 12)));
b = (57 - (1.8 * (srm - 12)));
} else { // srm > 22
r = (70 - (5.6 * (srm - 22)));
g = (40 - (3.1 * (srm - 22)));
b = (40 - (3.2 * (srm - 22)));
}
return rgb2hex(r, g, b);
}
function rgb2hex( r, g, b )
{
var rgb = [
lpad(parseInt(clamp(r, 0, 255)).toString(16), 2),
lpad(parseInt(clamp(g, 0, 255)).toString(16), 2),
lpad(parseInt(clamp(b, 0, 255)).toString(16), 2)
];
return rgb.join('');
}
function clamp ( val, min, max ) {
return Math.min(Math.max(val, min), max);
}
function lpad( val, max )
{
if (!max){ max = 2; }
var pad, padded = [];
pad = max - (val+'').length;
if (pad > 0){
while (pad--){ padded.push("0"); }
}
padded.push(val);
return padded.join('');
}
function setHtml( val )
{
var html = srm2hex(val);
$("#srmslider").slider("value", val);
$("#srmnum").val(val);
$("#srmhtml").val("#" + html);
$("#srmcolour").css('background-color', "#" + html);
}
function srmChanged()
{
var $this = $(this), val = $this.val(), is_float = (/\./).test(val), srm;
if (is_float || val == "") {
...