Andrei Oniga
Andrei Oniga

Reputation: 8559

RGB to HEX JavaScript function working in Chrome, but not Firefox or Safari

I recently found (on SO.com for that matter) a nifty little function that converts a RGB value to its hex correspondent. As an argument, I pass the values of the CSS "color" attributes (e.g.: "rgb(45,187,251)"). Here's the function:

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

It works perfectly in Chrome, but the Firebug console in Firefox gives the following error:

rgb is null

return "#" + hex(rgb1) + hex(rgb[2]) + hex(rgb[3]);

Why does this happen?

You can see it in use on goalcandy.com. Just hit "Start now", then click on "Save" on the left side of the screen and watch the Firebug console.

Upvotes: 2

Views: 595

Answers (2)

Andrei Oniga
Andrei Oniga

Reputation: 8559

It turned out not to be a problem with the rgb2hex() function, but rather with the jquery's css() method in Firefox. Namely, in Firefox, calling .css("border-color") returns a void value, as opposed to .css("border-top-color") for instance. Chrome understands the first version too.

Upvotes: 1

Stephen P
Stephen P

Reputation: 14800

Tracing though on that page using Firebug, in the call

data += rgb2hex(jqMesh.css('border-color')) + '|'

at line 1516 -- the call to jqMesh.css('border-color') is returning an empty string.

Calling jqMesh.css('color') in the Firebug console while stopped at that breakpoint returns "rgb(68, 68, 68)"

Upvotes: 1

Related Questions