What I'm trying to is:
- Pick up RGB value from an element
- Convert it to hex
- Put it into a text field
The first solution:
(taken from this thread RGB to Hex and Hex to RGB)
function rgbToHex(r, g, b) {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
The problem is: it only returns #aN
no matter what I feed it. Is the function flawed or am I doing something wrong?
The second solution:
From the same post as the upper mentioned.
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function rgbToHex(r, g, b) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
This works if I pass the value to as numbers rgbToHex(255,255,255)
but does nothing if I try to feed the numbers as a variable rgbToHex(rgbValue)
. (see the lines 19 to 25 in the demo)
All help appreciated :)