PDA

View Full Version : JasaScript, CSS and reading color properties



The_CyberShadow
12-13-2005, 01:08 AM
Subj.

I've written something, but it's hackish.


function rgb(r, g, b)
{
return (r<<16) + (g<<8) + b;
}

function colorToInt(s)
{
if(s.charAt(0)=='#' && s.length==7) // Opera
return parseInt("0x"+s.substring(1));

if(s.charAt(0)=='#' && s.length==4) // IE
return parseInt("0x"+s.charAt(1)+s.charAt(1)+s.charAt(2)+s.charAt(2)+s.charAt(3)+s.charAt(3));

if(s.substring(0, 3)=="rgb") // Netscape / Mozilla
return eval(s);

alert(s); // WTF
}

[...] var myColor = colorToInt(document.getElementById("myelement").style.color); [...]


Is there a proper way to do this?

jscheuer1
12-13-2005, 03:58 PM
That's not bad. What is your object in this? If the color is set in the stylesheet, through inheritance or via attribute, this:



var myColor = colorToInt(document.getElementById("myelement").style.color);

will not pick it up. Also, what will you do with this integer once you have it?

The_CyberShadow
12-15-2005, 11:56 AM
Well that's not much of an issue, that particular line I wrote out of my head to show the use of colorToInt.

My goal was to fade a page's background and contents to white, but keeping it proportional.

It's supposed to be for the loading intro of my homepage. You can find a working example of it here: http://maplecenter.net/thecybershadow/ (temporary URL).

jscheuer1
12-16-2005, 06:24 AM
Just a tip for simplifying your full code on this, which looks quite impressive and will provide hours of enjoyment trying to fully follow - To get the hex color value of the output of colorToInt(s) or any color represented as such an integer as this and other functions in your code produce:


hexColorValue='#'+colorIntegerValue.toString(16)

Twey
12-16-2005, 12:33 PM
Wouldn't it be easier to return an array of three values?

The_CyberShadow
12-16-2005, 05:54 PM
hexColorValue='#'+colorIntegerValue.toString(16)

That isn't quite correct. Suppose the value is less than 100000? Then the number would have 5 or less digits. Which is NOT what we want.

If you'll read fader.js on my site further, you'll find this function:


function toColor(i)
{
var s = i.toString(16)
while(s.length<6)
s='0'+s;
return '#'+s;
}

jscheuer1
12-16-2005, 06:48 PM
If you'll read fader.js on my site further, you'll find this function: . . .


. . . which looks quite impressive and will provide hours of enjoyment trying to fully follow . . .

:D

'nuff said?