Skip to main content

Background-color hex to JavaScript variable (jQuery)


I'm kind of new to JavaScript and jQuery and now I'm facing a problem:



I need to post some data to PHP and one bit of the data needs to be the background color hex of div X.



jQuery has the css("background-color") function and with it I can get RGB value of the background into a JavaScript variable.



The CSS function seems to return a string like this rgb(0, 70, 255).



I couldn't find any way to get hex of the background-color (even though it's set as hex in CSS).



So it seems like I need to convert it. I found a function for converting RGB to hex, but it needs to be called with three different variables, r, g and b. So I would need to parse the string rgb(x,xx,xxx) into var r=x; var g=xx; var b=xxx; somehow.



I tried to google parsing strings with JavaScript, but I didn't really understand the regular expressions thing.



Is there a way to get the background-color of div as hex, or can the string be converted into 3 different variables?


Source: Tips4allCCNA FINAL EXAM

Comments

  1. try this out:

    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 trying to modify the regex to handle both rgb and rgba depending which one I get. Any hints? Thanks.


    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+))?\)$/


    Example output:

    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"]

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

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


    It is valid CSS, don't worry.



    Edit: See nickf answer for a nice way to convert it if you absolutely need to.

    ReplyDelete
  3. 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

    Update, another better alternative method:

    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]);
    }

    ReplyDelete
  4. If you have jQuery available, this is the super-compact version that I just came up with.


    var RGBtoHEX = function(color) {
    return "#"+$.map(color.match(/\b(\d+)\b/g),function(digit){
    return ('0' + parseInt(digit).toString(16)).slice(-2)
    }).join('');
    };

    ReplyDelete
  5. With JQuery..

    var cssColorToHex = function(colorStr){
    var hex = '#';
    $.each(colorStr.substring(4).split(','), function(i, str){
    var h = ($.trim(str.replace(')',''))*1).toString(16);
    hex += (h.length == 1) ? "0" + h : h;
    });
    return hex;
    };

    ReplyDelete
  6. These solutions will fail in Chrome, as it returns an rgba(x,x,x,x) for background-color.

    EDIT: This is not necessarily true. Chrome will still set backgrounds using rgb(), depending on what you are doing. Most likely as long as there is no alpha channel applied, Chrome will respond with rgb instead of rgba.

    ReplyDelete
  7. http://www.phpied.com/rgb-color-parser-in-javascript/

    A JavaScript class that accepts a string and tries to figure out a valid color out of it. Some accepted inputs are for example:

    * rgb(0, 23, 255)
    * #336699
    * ffee66
    * fb0
    * red
    * darkblue
    * cadet blue

    ReplyDelete
  8. Here you go, this will allow you to use $(selector).getHexBackgroundColor() to return the hex value easily :

    $.fn.getHexBackgroundColor = function() {
    var rgb = $(this).css('background-color');
    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]);
    }

    ReplyDelete

Post a Comment

Popular posts from this blog

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex