If you have written HTML file, you must know that how to assign color to DOM element. You just need to assign CSS style to
DOM element like
It is very simple. But, we may want to change the color
<span style="color:#ff0000">This is text</span>
by Javascript like color picker. What's the problem? You may get the "rgb(255, 0, 0)" color value by Javascript.
Then, you have to convert rgb to hex color or convert hex to rgb color. The following is simple code.
rgb to hex
function rgb2hex(rgb){
var hexDigits = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f");
var hex = function(x){
return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
};
var tmp = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
var color = hex(tmp[1]) + hex(tmp[2]) + hex(tmp[3]);
return color;
}
hex to rgb
function hex2rgb(v){
if (/^[0-9A-F]{3}$|^[0-9A-F]{6}$/.test(v.toUpperCase())) {
if (v.length == 3) {
v = v.match(/[0-9A-F]/g);
v = v[0] + v[0] + v[1] + v[1] + v[2] + v[2];
this.value = v;
}
var r = parseInt(v.substr(0, 2), 16);
var g = parseInt(v.substr(2, 2), 16);
var b = parseInt(v.substr(4, 2), 16);
return [r, g, b].join(',');
}
return v;
}
Result
var input = $(this).css('color'); // rgb(255,0,0)
var hex = rgb2hex(input); //ff0000
var rgb = hex2rgb(hex); //255,0,0
I am sure that this is going to help a lot of individuals. Keep up the good work. It is highly convincing and I enjoyed going through the entire blog.
ReplyDeletebusiness analytics course
First You got a great blog .I will be interested in more similar topics. i see you got really very useful topics, i will be always checking your blog thanks.
ReplyDeletebest data science institute in hyderabad