daryl
daryl

Reputation: 15237

jquery # colour to rgba?

Is it possible to convert a colour as such #ff0000 to rgb?

So convert #ff0000 to rgb(255,0,0);

I'm pretty sure this has got to be possible, I just don't know how. Any insight would be great!

Upvotes: 5

Views: 6660

Answers (6)

Félix Saparelli
Félix Saparelli

Reputation: 8749

You have to separate all three components from the Hex definition, then convert them to decimal. This works:

function hex2rgba(x,a) {
  var r=x.replace('#','').match(/../g),g=[],i;
  for(i in r){g.push(parseInt(r[i],16));}g.push(a);
  return 'rgba('+g.join()+')';
}

Upvotes: 1

SeanCannon
SeanCannon

Reputation: 78046

Try this:

http://jsfiddle.net/AlienWebguy/AfVhs/1/

Upvotes: 0

Pascal MARTIN
Pascal MARTIN

Reputation: 401182

Purely working with the string you have, you could something like this :

var color = '#FF5500';

First, extract the two hexadecimal digits for each color :

var redHex = color.substring(1, 3);
var greenHex = color.substring(3, 5);
var blueHex = color.substring(5, 7);

Then, convert them to decimal :

var redDec = parseInt(redHex, 16);
var greenDec = parseInt(greenHex, 16);
var blueDec = parseInt(blueHex, 16);

And, finally, get your rgb() string as a result :

var colorRgb = 'rgb(' + redDec + ', ' + greenDec + ', ' + blueDec + ')';
console.log( colorRgb );

And you get as output :

rgb(255, 85, 0)

Upvotes: 3

Paul
Paul

Reputation: 141927

You could use:

var s = "#ff0000";
var patt = /^#([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})$/;
var matches = patt.exec(s);
var rgb = "rgb("+parseInt(matches[1], 16)+","+parseInt(matches[2], 16)+","+parseInt(matches[3], 16)+");";
alert(rgb);

Upvotes: 8

Vicente Plata
Vicente Plata

Reputation: 3380

What about this algorithm?

http://www.javascripter.net/faq/hextorgb.htm

You could even create a JQuery plugin that uses that algorithm. I think it would be cool. I don't know if there exists one already.

Upvotes: 3

Rafay
Rafay

Reputation: 31043

.css("background-color") will return rgb http://api.jquery.com/css/

here is the fiddle http://jsfiddle.net/3nigma/msRqv/1/

Upvotes: 6

Related Questions