14

I have a <div> whose transparency of its background-color (and not its contents) I'd like to change. A remote API sends me this colour:

#abcdef

and I tell jQuery (1.9) to apply this colour via .css:

$('div').css('background-color', '#abcdef');

The resultant div has a background-color style of not #abcdef, but rather its RGB representation of the same colour.

background-color: rgb(171, 205, 239);

(Just an observation; not part of the problem)


The project requirement has been changed such that I will now need to change the transparency of the background as well, to a set percentage (50%). My desired background-color attribute is thus

background-color: rgba(171, 205, 239, 0.5);

, however, I cannot find a way to set this background-color attribute using just jQuery, a hex colour code, and still apply an alpha value. opacity affects contents of the div as well as the background, so it is not an option.

$('div').css('background-color', '#abcdef')
        .css('opacity', 0.5);  // undesirable opacity changes to div's content

Given the string #abcdef, is it possible only by calculation (e.g. hex2dec) that I will be able to apply a background opacity to a div if I am given only a hex colour string?

Brian
  • 7,394
  • 3
  • 25
  • 46
  • I don't think you can set bg opacity with a hex value. You could split the hex into value pairs and turn it into a decimal so you can create an rgba setting on the fly, but it would *not* be pretty. – Rory McCrossan Oct 29 '13 at 16:05
  • What's wrong with this `$('div').css('background-color', 'rgba(171, 205, 239, 0.5)')` ? – The Alpha Oct 29 '13 at 16:07
  • @RoryMcCrossan tried `$('div').css('background-color', '#abcdef77')` -- jQuery ain't fooled. Heh. – Brian Oct 29 '13 at 16:07
  • You cant set bg opacity with a hex value, your options are using rgba or a small png. RGBA would be best and if you need to cater for ie7 then CSS3 Pie will help you out in that department – craigie2204 Oct 29 '13 at 16:07
  • You are right @RecoveringSince2003, your proposal is the only one that would work, *if only the API provides me with that value*. It doesn't... so this question exists. @-Twocode that affects content opacity. – Brian Oct 29 '13 at 16:10
  • Also you can embed div's content into another div with transparent background and 100% opacity, than original div's opacity will not affect content. – mas.morozov Oct 29 '13 at 16:11
  • @Brian check out the answer to [this question](http://stackoverflow.com/questions/6805740/jquery-colour-to-rgba) - it shows how to convert hex to rgba. You can then provide your own opacity value. – Rory McCrossan Oct 29 '13 at 16:11
  • @RoryMcCrossan my fears exactly, having to convert hex to dec in JS... [I love SASS](http://stackoverflow.com/questions/10929458/sass-converting-hex-to-rgba-for-background-opacity), but it cannot be used here. – Brian Oct 29 '13 at 16:13
  • can try this solution: [link](http://stackoverflow.com/questions/10929458/sass-converting-hex-to-rgba-for-background-opacity) – Venzentx Oct 29 '13 at 16:23
  • @Twocode isn't that the exact same link in the comment above you? – Brian Oct 29 '13 at 16:25
  • @Brian didnt check others, but Google gives people the same thing :P – Venzentx Oct 30 '13 at 10:10

4 Answers4

20

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.

Pranav Gupta
  • 944
  • 6
  • 11
10

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.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
  • Given my circumstances, both (similar) workarounds will have to do. Thanks! – Brian Oct 29 '13 at 16:21
  • IE11 might be mutilating my ie8 filters. Started thread here: http://stackoverflow.com/questions/29926860/jquery-dynamic-background-alpha-in-ie8-ms-filter – Jen Apr 28 '15 at 18:48
  • Opacity is mostly presented as `0.5` instead of `50`. So the code should be changed to accept `convertHex('#A7D136', 0.5)`, and the last line should be changed to: `result = 'rgba('+r+','+g+','+b+','+ opacity + ')';` – Aleks Apr 24 '17 at 13:50
3

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;
}
Ruwen
  • 3,008
  • 1
  • 19
  • 16
0

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

Martin
  • 1,216
  • 8
  • 15