I have a
You may try this
function convertHex(hex,opacity){
hex = hex.replace('#','');
r = parseInt(hex.substring(0,2), 16);
g = parseInt(hex.substring(2,4), 16);
b = parseInt(hex.substring(4,6), 16);
result = 'rgba('+r+','+g+','+b+','+opacity/100+')';
return result;
}
$('h1').css('background', convertHex('#A7D136', 0.5));
An example here.
try parseInt(hex,16)
to convert hex string into decimal int
so in this case it'll be:
var color = '#abcdef';
var rgbaCol = 'rgba(' + parseInt(color.slice(-6,-4),16)
+ ',' + parseInt(color.slice(-4,-2),16)
+ ',' + parseInt(color.slice(-2),16)
+',0.5)';
$('div').css('background-color', rgbaCol)
you should create a function out of this to use in your application.
You may use this javascript helper function
function setColorOpacity(colorStr, opacity) {
if(colorStr.indexOf("rgb(") == 0)
{
var rgbaCol = colorStr.replace("rgb(", "rgba(");
rgbaCol = rgbaCol.replace(")", ", "+opacity+")");
return rgbaCol;
}
if(colorStr.indexOf("rgba(") == 0)
{
var rgbaCol = colorStr.substr(0, colorStr.lastIndexOf(",")+1) + opacity + ")";
return rgbaCol;
}
if(colorStr.length == 6)
colorStr = "#" + colorStr;
if(colorStr.indexOf("#") == 0)
{
var rgbaCol = 'rgba(' + parseInt(colorStr.slice(-6, -4), 16)
+ ',' + parseInt(colorStr.slice(-4, -2), 16)
+ ',' + parseInt(colorStr.slice(-2), 16)
+ ','+opacity+')';
return rgbaCol;
}
return colorStr;
}
This should work for you. It does assume that you are passing a valid 6 digit hex code and an opacity, and does no error checking.
function hex2rgba(hex, opacity)
{
//extract the two hexadecimal digits for each color
var patt = /^#([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})$/;
var matches = patt.exec(hex);
//convert them to decimal
var r = parseInt(matches[1], 16);
var g = parseInt(matches[2], 16);
var b = parseInt(matches[3], 16);
//create rgba string
var rgba = "rgba(" + r + "," + g + "," + b + "," + opacity + ")";
//return rgba colour
return rgba;
}
$(".box").css("background-color", hex2rgba("#ABCDEF", 0.6));
You can view an example of this on jsFiddle here