My fiddle - http://jsbin.com/pitu/1/edit
I wanted to try an easy hex to rgba conversion. Ever browser I\'ve used renders colors using rgb as default so when using th
Convert HEX with alpha (ahex) in to rgba.
function ahex_to_rba(ahex) {
//clean #
ahex = ahex.substring(1, ahex.length);
ahex = ahex.split('');
var r = ahex[0] + ahex[0],
g = ahex[1] + ahex[1],
b = ahex[2] + ahex[2],
a = ahex[3] + ahex[3];
if (ahex.length >= 6) {
r = ahex[0] + ahex[1];
g = ahex[2] + ahex[3];
b = ahex[4] + ahex[5];
a = ahex[6] + (ahex[7] ? ahex[7] : ahex[6]);
}
var int_r = parseInt(r, 16),
int_g = parseInt(g, 16),
int_b = parseInt(b, 16),
int_a = parseInt(a, 16);
int_a = int_a / 255;
if (int_a < 1 && int_a > 0) int_a = int_a.toFixed(2);
if (int_a || int_a === 0)
return 'rgba('+int_r+', '+int_g+', '+int_b+', '+int_a+')';
return 'rgb('+int_r+', '+int_g+', '+int_b+')';
}
Try it yourself with snippet:
function ahex_to_rba(ahex) {
//clean #
ahex = ahex.substring(1, ahex.length);
ahex = ahex.split('');
var r = ahex[0] + ahex[0],
g = ahex[1] + ahex[1],
b = ahex[2] + ahex[2],
a = ahex[3] + ahex[3];
if (ahex.length >= 6) {
r = ahex[0] + ahex[1];
g = ahex[2] + ahex[3];
b = ahex[4] + ahex[5];
a = ahex[6] + (ahex[7] ? ahex[7] : ahex[6]);
}
var int_r = parseInt(r, 16),
int_g = parseInt(g, 16),
int_b = parseInt(b, 16),
int_a = parseInt(a, 16);
int_a = int_a / 255;
if (int_a < 1 && int_a > 0) int_a = int_a.toFixed(2);
if (int_a || int_a === 0)
return 'rgba('+int_r+', '+int_g+', '+int_b+', '+int_a+')';
return 'rgb('+int_r+', '+int_g+', '+int_b+')';
}
$(function() {
$('#go').click(function() {
$('p b').text(ahex_to_rba($('#hex').val()));
})
});
Result:
Original Author