47

I have an element like this:

<p>My text with a <strong class="highlighted">sample highlight</strong>.<p>

And the CSS class like this:

.highlighted {
    background: #f0ff05;
    font-weight: normal;
}

But when I use a jQuery like this:

$(".highlighted").css("backgroundColor");

It returns rgb(240, 255, 5). I could write some function to convert from rgb to hex, but I would like to know if there is some way to jQuery return the value already on hexadecimal format.

Erick Petrucelli
  • 14,386
  • 8
  • 64
  • 84
  • 1
    Nope. There is no jquery method or property for doing this. Start to write your own code. Take a look at here, http://stackoverflow.com/questions/1740700/get-hex-value-rather-than-rgb-value-using-jquery – miqbal May 30 '11 at 14:27
  • Why do you need it in hex? Isn't `rgb` easier to parse? – Eric May 30 '11 at 15:11
  • I'll send the hex value using AJAX and the server-side code (Which I can not change) expects on hex. –  May 30 '11 at 15:14

3 Answers3

76

Colors are always returned as rgb (except IE6 which already returns in hex), then we cannot return in another format natively.

Like you said, you can write a function to convert hex to rgb. Here is a topic with several examples of how to write this function: How to get hex color value rather than RGB value?.

But you wonder if there is a way to directly return the jQuery already in hex: the answer is yes, this is possible using CSS Hooks since jQuery 1.4.3.

The code should be:

$.cssHooks.backgroundColor = {
    get: function(elem) {
        if (elem.currentStyle)
            var bg = elem.currentStyle["backgroundColor"];
        else if (window.getComputedStyle)
            var bg = document.defaultView.getComputedStyle(elem,
                null).getPropertyValue("background-color");
        if (bg.search("rgb") == -1)
            return bg;
        else {
            bg = bg.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
            function hex(x) {
                return ("0" + parseInt(x).toString(16)).slice(-2);
            }
            return "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);
        }
    }
}

And when you call $(".highlighted").css("backgroundColor"), the return will be #f0ff05. Here is a working sample to you see it working.

Community
  • 1
  • 1
Erick Petrucelli
  • 14,386
  • 8
  • 64
  • 84
  • But your code only have the `get`. I'll can use `$(".highlight").css("backgroundColor", "#ff0000")` yet? –  May 30 '11 at 14:29
  • Since we aren't overriding the setter, it you remains working without changes. My working sample has a set example. – Erick Petrucelli May 30 '11 at 14:33
  • Cool, I haven't seen this in the example. Thanks! –  May 30 '11 at 14:39
  • I'm not sure if it is just the machine I am testing on, but IE8 is throwing an exception trying to use this shim. It throws an undefined error for bg on the line `if (bg.search("rgb") == -1)`, which means bg isn't being defined from the first if else statement. It should be noted that I am only experiencing this on an actual version of IE8 and not in IE9 using the dev tools to simulate IE8. – Paul T Oct 09 '12 at 22:01
  • @PaulT, I haven't any machine with IE8 now to test it. But maybe IE8 haven't `currentStyle` nor `getComputedStyle`, so we would need to create one more else to retrieve the `background-color` in another way. I'm not sure which way, but if you find it, please post here and I'll updating the answer. – Erick Petrucelli Oct 10 '12 at 20:08
  • 4
    To make this compatibile in IE8 change `var bg = elem.currentStyle["background-color"];` to `var bg = elem.currentStyle["backgroundColor"];` – dloewen Dec 06 '12 at 16:40
  • Thanks @dloewen, I updated the code with your suggestion. I'm not on IE8 for testing it, but if there are more troubles, let me know. – Erick Petrucelli Dec 06 '12 at 17:08
  • Very cool! I tried to use it and couldn't make it work... Browser returns rgbA. A little tweak is required to make it work correctly. – Salketer Jan 14 '13 at 09:34
  • Thanks by your feedback @Salketer, can you please share what browser version on what OS? – Erick Petrucelli Jan 14 '13 at 12:08
  • @ErickPetru , you're right I dunno why I did not say... Chrome 24.0.1312 on Win8. After some testing, turns out RGBA is returned why the background-color is UNDEFINED, so it returns rgba(0,0,0,0). People might want to test on the Alpha to decide on what RGB to use... I personnally decided to retreive the parents' background-color if RGBA returns 0 Alpha... – Salketer Jan 14 '13 at 13:39
  • don't forget radix: parseInt(x, 10) – Bob Aug 12 '15 at 04:44
  • @Mary, according to MDN, "the ECMAScript 5 specification of the function *parseInt* no longer allows implementations to treat Strings beginning with a 0 character as octal values", so radix param for decimal base conversions isn't needed on all modern browsers. – Erick Petrucelli Aug 14 '15 at 13:17
  • Yes @MatiK, when I answered the only OP concern was RGB. But take a look [at this answer](http://stackoverflow.com/a/3971432/424498) based on my original code allowing proper RGBA detection. – Erick Petrucelli Oct 14 '15 at 17:56
1

This is a slightly adjusted version of Erick Petrucelli's answer. It appears to handle RGBA.

$.cssHooks.backgroundColor = {
  get: function (elem) {
    if (elem.currentStyle) var bg = elem.currentStyle["backgroundColor"];
    else if (window.getComputedStyle)
      var bg = document.defaultView
        .getComputedStyle(elem, null)
        .getPropertyValue("background-color");
    if (bg.search("rgba") > -1) {
      return "#00ffffff";
    } else {
      if (bg.search("rgb") == -1) {
        return bg;
      } else {
        bg = bg.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
        function hex(x) {
          return ("0" + parseInt(x).toString(16)).slice(-2);
        }
        return "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);
      }
    }
  },
};
lebol
  • 433
  • 5
  • 12
li3
  • 41
  • 5
0
function RGBAToHexA(test:string) {
let sep = test.toString().indexOf(",") > -1 ? "," : " ";
const rgba = test.toString().substring(5).split(")")[0].split(sep);
console.log(rgba)
let r = (+rgba[0]).toString(16),
  g = (+rgba[1]).toString(16),
  b = (+rgba[2]).toString(16),
  a = Math.round(+rgba[3] * 255).toString(16);

    if (r.length == 1)
        r = "0" + r;
    if (g.length == 1)
        g = "0" + g;
    if (b.length == 1)
        b = "0" + b;
    if (a.length == 1)
        a = "0" + a;

return "#" + r + g + b + a;}

This code works fine for me, I am using Jasmine protractor and I was getting rgb format when I tried to getcssValue of an element.

it('should check color  of login btn', async function(){
    browser.waitForAngularEnabled(true);
    browser.actions().mouseMove(element(by.css('.btn-auth, .btn-auth:hover'))).perform(); // mouse hover on button
    csspage.Loc_auth_btn.getCssValue('color').then(function(color){
        console.log(RGBAToHexA(color))
        expect( RGBAToHexA(color)).toContain(cssData.hoverauth.color);

    })
   // expect(csspage.Loc_auth_btn.getCssValue('color')).toContain(cssData.hoverauth.color);
})