Rectangle 27 67

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.

$.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]);
        }
    }
}
$(".highlighted").css("backgroundColor")
#f0ff05
get
$(".highlight").css("backgroundColor", "#ff0000")

Since we aren't overriding the setter, it you remains working without changes. My working sample has a set example.

var bg = elem.currentStyle["background-color"];
var bg = elem.currentStyle["backgroundColor"];

rgb - Can I force jQuery.css("backgroundColor") returns on hexadecimal...

jquery rgb hex background-color
Rectangle 27 8

You can set a CSS color using rgb also, such as this:

background-color: rgb(0, 70, 255);

jquery - Background-color hex to JavaScript variable - Stack Overflow

javascript jquery hex rgb background-color
Rectangle 27 5

I found another function awhile back (by R0bb13). It doesn't have the regex, so I had to borrow it from nickf to make it work properly. I'm only posting it because it's an interesting method that doesn't use an if statement or a loop to give you a result. Also this script returns the hex value with a # (It was needed by the Farbtastic plugin I was using at the time)

//Function to convert hex format to a rgb color
function rgb2hex(rgb) {
 var hexDigits = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 function hex(x) {
  return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
 }
 return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

// call the function: rgb( "rgb(0, 70, 255)" );
// returns: #0046ff

Note: The hex result from nickf's script should be 0046ff and not 0070ff, but no big deal :P

function rgb2hex(rgb) {
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 function hex(x) {
  return ("0" + parseInt(x).toString(16)).slice(-2);
 }
 return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

I would rather move function hex(x) out of the scope of fucntion rgb2hex for performance improvement. Anyway it's a nice clean solution, thanks for sharing. Have a look at mine below, I would like your opinion.

jquery - Background-color hex to JavaScript variable - Stack Overflow

javascript jquery hex rgb background-color
Rectangle 27 113

var hexDigits = new Array
        ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"); 

//Function to convert rgb color to hex format
function rgb2hex(rgb) {
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

function hex(x) {
  return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
 }

-1. As mentioned by orip, you could use toString(16). Downvoted for other inefficiencies. If you're going to declare hexDigits on every function call, at least do it in rgb2hex's function body (not hex's body), so the array is not redefined 3 times per 1 call to rgb2hex. Also learn to use 'var', so you don't pollute the global scope.

This method does not seem very tolerant of differing white-space or capitalisation. jsfiddle.net/Xotic750/pSQ7d

If you realy want to be pedantic, you can make the regex more permissive: rgb.match(/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i) However, the regex given is designed to cope with the format given by a browser when using jQuery, and this doesn't have the different white-space or captilisation consistencies you are talking about. You could also use the same regex and just remove all whitespaces and convert to lowercase before matching on rgb. P.S. Your fiddle example: 'rgb(10, 128,)' I don't think that is reasonable to test on

and for me the return of jquery css background-colors comes in format with rgba , so this does not works.

javascript - How to get hex color value rather than RGB value? - Stack...

javascript jquery colors hex rgb
Rectangle 27 113

var hexDigits = new Array
        ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"); 

//Function to convert rgb color to hex format
function rgb2hex(rgb) {
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

function hex(x) {
  return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
 }

-1. As mentioned by orip, you could use toString(16). Downvoted for other inefficiencies. If you're going to declare hexDigits on every function call, at least do it in rgb2hex's function body (not hex's body), so the array is not redefined 3 times per 1 call to rgb2hex. Also learn to use 'var', so you don't pollute the global scope.

This method does not seem very tolerant of differing white-space or capitalisation. jsfiddle.net/Xotic750/pSQ7d

If you realy want to be pedantic, you can make the regex more permissive: rgb.match(/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i) However, the regex given is designed to cope with the format given by a browser when using jQuery, and this doesn't have the different white-space or captilisation consistencies you are talking about. You could also use the same regex and just remove all whitespaces and convert to lowercase before matching on rgb. P.S. Your fiddle example: 'rgb(10, 128,)' I don't think that is reasonable to test on

and for me the return of jquery css background-colors comes in format with rgba , so this does not works.

javascript - How to get hex color value rather than RGB value? - Stack...

javascript jquery colors hex rgb
Rectangle 27 1

I came across this problem since I wanted to accept any color value and be able to add an opacity, so I made this quick jQuery plugin that uses the native canvas on modern browsers. Seems to work just great.

Turns out I can't figure out how to make it a proper jQuery plugin, so I'll just present it as a regular function.

//accepts any value like '#ffffff', 'rgba(255,255,255,1)', 'hsl(0,100%,100%)', or 'white'
function toRGBA( c ) {
    var
        can  = document.createElement( 'canvas' ),
        ctx  = can.getContext( '2d' );
    can.width = can.height = 1;
    ctx.fillStyle = c;
    console.log( ctx.fillStyle ); //always css 6 digit hex color string, e.g. '#ffffff'
    ctx.fillRect( 0, 0, 1, 1 ); //paint the canvas
    var
        img  = ctx.getImageData( 0, 0, 1, 1 ),
        data = img.data,
        rgba = {
            r: data[ 0 ], //0-255 red
            g: data[ 1 ], //0-255 green
            b: data[ 2 ], //0-255 blue
            a: data[ 3 ]  //0-255 opacity (0 being transparent, 255 being opaque)
        };
    return rgba;
};

javascript - RGB to Hex and Hex to RGB - Stack Overflow

javascript colors hex rgb
Rectangle 27 1

I came across this problem since I wanted to accept any color value and be able to add an opacity, so I made this quick jQuery plugin that uses the native canvas on modern browsers. Seems to work just great.

Turns out I can't figure out how to make it a proper jQuery plugin, so I'll just present it as a regular function.

//accepts any value like '#ffffff', 'rgba(255,255,255,1)', 'hsl(0,100%,100%)', or 'white'
function toRGBA( c ) {
    var
        can  = document.createElement( 'canvas' ),
        ctx  = can.getContext( '2d' );
    can.width = can.height = 1;
    ctx.fillStyle = c;
    console.log( ctx.fillStyle ); //always css 6 digit hex color string, e.g. '#ffffff'
    ctx.fillRect( 0, 0, 1, 1 ); //paint the canvas
    var
        img  = ctx.getImageData( 0, 0, 1, 1 ),
        data = img.data,
        rgba = {
            r: data[ 0 ], //0-255 red
            g: data[ 1 ], //0-255 green
            b: data[ 2 ], //0-255 blue
            a: data[ 3 ]  //0-255 opacity (0 being transparent, 255 being opaque)
        };
    return rgba;
};

javascript - RGB to Hex and Hex to RGB - Stack Overflow

javascript colors hex rgb
Rectangle 27 8

$.fn.getHexBackgroundColor = function() {
    var rgb = $(this).css('background-color');
    if (!rgb) {
        return '#FFFFFF'; //default color
    }
    var hex_rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); 
    function hex(x) {return ("0" + parseInt(x).toString(16)).slice(-2);}
    if (hex_rgb) {
        return "#" + hex(hex_rgb[1]) + hex(hex_rgb[2]) + hex(hex_rgb[3]);
    } else {
        return rgb; //ie8 returns background-color in hex format then it will make                 compatible, you can improve it checking if format is in hexadecimal
    }
}

jquery css color value returns RGB? - Stack Overflow

jquery css hex rgb
Rectangle 27 8

$.fn.getHexBackgroundColor = function() {
    var rgb = $(this).css('background-color');
    if (!rgb) {
        return '#FFFFFF'; //default color
    }
    var hex_rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); 
    function hex(x) {return ("0" + parseInt(x).toString(16)).slice(-2);}
    if (hex_rgb) {
        return "#" + hex(hex_rgb[1]) + hex(hex_rgb[2]) + hex(hex_rgb[3]);
    } else {
        return rgb; //ie8 returns background-color in hex format then it will make                 compatible, you can improve it checking if format is in hexadecimal
    }
}

jquery css color value returns RGB? - Stack Overflow

jquery css hex rgb
Rectangle 27 55

Most browsers seem to return the RGB value when using:

$('#selector').css('backgroundColor');

Only I.E (only 6 tested so far) returns the Hex value.

To avoid error messages in I.E, you could wrap the function in an if statement:

function rgb2hex(rgb) {
     if (  rgb.search("rgb") == -1 ) {
          return rgb;
     } else {
          rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
          function hex(x) {
               return ("0" + parseInt(x).toString(16)).slice(-2);
          }
          return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); 
     }
}

This one works better than most others, since Jim takes rgba into account, which is what Safari (at least on Mac OS X) uses. Thanks, Jim!

Great solution. Note that function returns lower case letters i.e. #ff5544 not #FF5544.

javascript - How to get hex color value rather than RGB value? - Stack...

javascript jquery colors hex rgb
Rectangle 27 55

Most browsers seem to return the RGB value when using:

$('#selector').css('backgroundColor');

Only I.E (only 6 tested so far) returns the Hex value.

To avoid error messages in I.E, you could wrap the function in an if statement:

function rgb2hex(rgb) {
     if (  rgb.search("rgb") == -1 ) {
          return rgb;
     } else {
          rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
          function hex(x) {
               return ("0" + parseInt(x).toString(16)).slice(-2);
          }
          return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); 
     }
}

This one works better than most others, since Jim takes rgba into account, which is what Safari (at least on Mac OS X) uses. Thanks, Jim!

Great solution. Note that function returns lower case letters i.e. #ff5544 not #FF5544.

javascript - How to get hex color value rather than RGB value? - Stack...

javascript jquery colors hex rgb
Rectangle 27 1

For convert directly from jQuery you can try:

function rgbToHex(color) {
    var bg = color.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]);
  }

  rgbToHex($('.col-tab-bar .col-tab span').css('color'))

javascript - RGB to Hex and Hex to RGB - Stack Overflow

javascript colors hex rgb
Rectangle 27 1

For convert directly from jQuery you can try:

function rgbToHex(color) {
    var bg = color.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]);
  }

  rgbToHex($('.col-tab-bar .col-tab span').css('color'))

javascript - RGB to Hex and Hex to RGB - Stack Overflow

javascript colors hex rgb
Rectangle 27 3

I've created a function that uses readable basic functions and no reg-exps. The function accepts color in hex, rgb or rgba CSS format and returns hex representation. EDIT: there was a bug with parsing out rgba() format, fixed...

function getHexColor( color ){
    //if color is already in hex, just return it...
    if( color.indexOf('#') != -1 ) return color;

    //leave only "R,G,B" :
    color = color
                .replace("rgba", "") //must go BEFORE rgb replace
                .replace("rgb", "")
                .replace("(", "")
                .replace(")", "");
    color = color.split(","); // get Array["R","G","B"]

    // 0) add leading #
    // 1) add leading zero, so we get 0XY or 0X
    // 2) append leading zero with parsed out int value of R/G/B
    //    converted to HEX string representation
    // 3) slice out 2 last chars (get last 2 chars) => 
    //    => we get XY from 0XY and 0X stays the same
    return  "#"
            + ( '0' + parseInt(color[0], 10).toString(16) ).slice(-2)
            + ( '0' + parseInt(color[1], 10).toString(16) ).slice(-2)
            + ( '0' + parseInt(color[2], 10).toString(16) ).slice(-2);
}
.replace("rgba", "")                 .replace("rgb", "")                 .replace("(", "")                 .replace(")", "");

If the 4th value in an rgba is 0 (zero), then for css for that 'element' would be: element{ color: #000000, opacity: 0.0;} which is transparent or just conditionally return the 'rgba(0,0,0,0)' back to the caller.

@Twelve24 Parsing fixed - I actually noticed that before reading your comment, but definitely thanks for that :) , As for transparency - function is supposed to return HEXA color, or the "base color" - so that one is on purpose :)

javascript - How to get hex color value rather than RGB value? - Stack...

javascript jquery colors hex rgb
Rectangle 27 3

I've created a function that uses readable basic functions and no reg-exps. The function accepts color in hex, rgb or rgba CSS format and returns hex representation. EDIT: there was a bug with parsing out rgba() format, fixed...

function getHexColor( color ){
    //if color is already in hex, just return it...
    if( color.indexOf('#') != -1 ) return color;

    //leave only "R,G,B" :
    color = color
                .replace("rgba", "") //must go BEFORE rgb replace
                .replace("rgb", "")
                .replace("(", "")
                .replace(")", "");
    color = color.split(","); // get Array["R","G","B"]

    // 0) add leading #
    // 1) add leading zero, so we get 0XY or 0X
    // 2) append leading zero with parsed out int value of R/G/B
    //    converted to HEX string representation
    // 3) slice out 2 last chars (get last 2 chars) => 
    //    => we get XY from 0XY and 0X stays the same
    return  "#"
            + ( '0' + parseInt(color[0], 10).toString(16) ).slice(-2)
            + ( '0' + parseInt(color[1], 10).toString(16) ).slice(-2)
            + ( '0' + parseInt(color[2], 10).toString(16) ).slice(-2);
}
.replace("rgba", "")                 .replace("rgb", "")                 .replace("(", "")                 .replace(")", "");

If the 4th value in an rgba is 0 (zero), then for css for that 'element' would be: element{ color: #000000, opacity: 0.0;} which is transparent or just conditionally return the 'rgba(0,0,0,0)' back to the caller.

@Twelve24 Parsing fixed - I actually noticed that before reading your comment, but definitely thanks for that :) , As for transparency - function is supposed to return HEXA color, or the "base color" - so that one is on purpose :)

javascript - How to get hex color value rather than RGB value? - Stack...

javascript jquery colors hex rgb
Rectangle 27 2

maybe you could convert the RGB color ro HSL or HSB / HSV then apply the variation and then back to RGB!

look here -> http://www.easyrgb.com/index.php?X=MATH <- for formulas for converting from and to HSL / HSB/ HSV and others...

How to Calculate RGB Hex Color Variations with Javascript/jQuery - Sta...

javascript jquery colors hex
Rectangle 27 1

A little play with hex - from any given color increment\decrement with a certain step until the end of the scale, white(fff shortened from ffffff) or black (000 - form 000000).

How to Calculate RGB Hex Color Variations with Javascript/jQuery - Sta...

javascript jquery colors hex
Rectangle 27 62

var rgbString = "rgb(0, 70, 255)"; // get this in whatever way.

var parts = rgbString.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
// parts now should be ["rgb(0, 70, 255", "0", "70", "255"]

delete (parts[0]);
for (var i = 1; i <= 3; ++i) {
    parts[i] = parseInt(parts[i]).toString(16);
    if (parts[i].length == 1) parts[i] = '0' + parts[i];
} 
var hexString ='#'+parts.join('').toUpperCase(); // "#0070FF"

In response to the question in the comments below:

I'm not exactly sure if it makes sense in the context of this question (since you can't represent an rgba color in hex), but I guess there could be other uses. Anyway, you could change the regex to be like this:

/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(0\.\d+))?\)$/
var d = document.createElement('div');
d.style.backgroundColor = 'rgba( 255,  60, 50, 0)';

/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(1|0\.\d+))?\)$/.exec(d.style.backgroundColor);

// ["rgba(255, 60, 50, 0.33)", "255", "60", "50", "0.33"]

@Neal or anyone else having that issue: In IE, jquery 1.4.4 returns the hex code instead of the rgb string. So parts is null because the regex doesn't match, which causes an error when parts is used. I had to add a check before the delete and return the original string if parts is null.

@nickf forgot to thank you for that from before. btw I added /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(1|0|0\.\d+))?\)$/ the |0 near the end to check when alpha is just 0 and not 0.x

(1|0|0?\.d+)
.3

jquery - Background-color hex to JavaScript variable - Stack Overflow

javascript jquery hex rgb background-color
Rectangle 27 142

Here is the cleaner solution I wrote based on @Matt suggestion:

function rgb2hex(rgb) {
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

Some browsers already returns colors as hexadecimal (as of Internet Explorer 8 and below). If you need to deal with those cases, just append a condition inside the function, like @gfrobenius suggested:

function rgb2hex(rgb) {
    if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb;

    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

If you're using jQuery and want a more complete approach, you can use CSS Hooks available since jQuery 1.4.3, as I showed when answering this question: Can I force jQuery.css("backgroundColor") returns on hexadecimal format?

This won't work on IE8. Too bad.

@Ghigo, sorry but you are wrong. IE8 already returns colors as hexadecimal when getting the current style, this way: document.getElementById("your_id").currentStyle["backgroundColor"]. The function rgb2hex() isn't needed. Here's the jQuery plugin using CSS Hooks that I suggested above, which already does all the validations to recover colors in different browsers: stackoverflow.com/questions/6177454/

@Ghigo, I think you misunderstand: you SHOULD NOT use this function if you are in a browser that returns in HEX. This function convert RGB to HEX and just it. Do not use it when it's not in RGB. The fact that you need a more complete solution (which detects if the value is already as RGB, as made by @Jim-F) don't change the fact that this solution offers exactly what was requested by the OP. Your downvote makes no sense, sorry.

I'm sorry but I do not agree. A cross browser function is always better than one that need execution based on browser detection. Op asked to convert $('#selector').css('backgroundColor') to hex, not a rgb value to hex. And on IE8, $('#selector').css('backgroundColor') is already hex so it must be handled. That's it. Don't get mad at me :)

javascript - How to get hex color value rather than RGB value? - Stack...

javascript jquery colors hex rgb
Rectangle 27 142

Here is the cleaner solution I wrote based on @Matt suggestion:

function rgb2hex(rgb) {
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

Some browsers already returns colors as hexadecimal (as of Internet Explorer 8 and below). If you need to deal with those cases, just append a condition inside the function, like @gfrobenius suggested:

function rgb2hex(rgb) {
    if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb;

    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

If you're using jQuery and want a more complete approach, you can use CSS Hooks available since jQuery 1.4.3, as I showed when answering this question: Can I force jQuery.css("backgroundColor") returns on hexadecimal format?

This won't work on IE8. Too bad.

@Ghigo, sorry but you are wrong. IE8 already returns colors as hexadecimal when getting the current style, this way: document.getElementById("your_id").currentStyle["backgroundColor"]. The function rgb2hex() isn't needed. Here's the jQuery plugin using CSS Hooks that I suggested above, which already does all the validations to recover colors in different browsers: stackoverflow.com/questions/6177454/

@Ghigo, I think you misunderstand: you SHOULD NOT use this function if you are in a browser that returns in HEX. This function convert RGB to HEX and just it. Do not use it when it's not in RGB. The fact that you need a more complete solution (which detects if the value is already as RGB, as made by @Jim-F) don't change the fact that this solution offers exactly what was requested by the OP. Your downvote makes no sense, sorry.

I'm sorry but I do not agree. A cross browser function is always better than one that need execution based on browser detection. Op asked to convert $('#selector').css('backgroundColor') to hex, not a rgb value to hex. And on IE8, $('#selector').css('backgroundColor') is already hex so it must be handled. That's it. Don't get mad at me :)

javascript - How to get hex color value rather than RGB value? - Stack...

javascript jquery colors hex rgb