I honestly can't think of a better title, I'm new with writing my own javascript.
Basically, I have the following script which will translate a hex value to an rgb value:
$(".submit").click(function() {
function hex2rgb(hex) {
if (hex.length < 3) {
$(".result").text("Error");
}
if (hex[0] == "#") {
hex = hex.substr(1);
}
if (hex.length == 3) {
var temp = hex;
hex = '';
temp = /^([a-f0-9])([a-f0-9])([a-f0-9])$/i.exec(temp).slice(1);
for (var i = 0; i < 3; i++) hex += temp[i] + temp[i];
}
var triplets = /^([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i.exec(hex).slice(1);
return {
red: parseInt(triplets[0], 16),
green: parseInt(triplets[1], 16),
blue: parseInt(triplets[2], 16)
}
}
var hex = $(".hex").val();
var rgb = hex2rgb("#" + hex);
$(".result").text("rgba(" + rgb.red + "," + rgb.green + "," + rgb.blue + ",1)");
});
Working example: http://jsfiddle.net/charlescarver/JkeKV/5/
When the number of digits entered in the textbox is less than 3 (an incomplete hex code), it changes the text of .result to error. The code itself works fine, but the console is throwing up an error saying...
TypeError: 'null' is not an object (evaluating '/^([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i.exec(hex).slice')
I assumed that if the code was less than 3 digits, it would just display the error, not try to move on to if (hex.length == 3) {} function, which it seems like it is doing. Is any of this correct?
Also, would it be better to use if (hex.length == 3) {} or if (hex.length >= 3) { for the function that translates the hex to rgb? I'm only thinking this because the number of digits has to be 3 >= x <= 6?
#333would be the same as#333333.