Previous Page
Next Page

Converting RGB Values to Hex

Another useful little widget Web developers frequently wish they had on hand is an RGB-to-hexadecimal converter. This is useful whenever you need to translate a color value from a graphics program like Adobe Photoshop or Macromedia Fireworks into a browser color, for page backgrounds or text colors. Script 17.10 shows the conversion calculator done in JavaScript and turned into a bookmarklet.

Script 17.10. This script takes RGB color values and turns them into their hexadecimal equivalents.

javascript:var s,i,n,h='',x='0123456789ABCDEF',c= prompt('R,G,B:','');if(c){s=c.split(',
'); for(i=0;i<3;i++){n=parseInt(s[i]);h+=x.charAt (n>>4)+x.charAt(n&15)}void(prompt (
'Hexcolor:','#'+h))}else{void(null);}

To convert RGB values to hexadecimal:

1.
javascript:var s,i,n,h='',



Start off the bookmarklet by initializing four variables.

2.
x='0123456789ABCDEF',



The variable x is set to the valid hexadecimal values.

3.
c=prompt('R,G,B:','');



This line prompts the user for the requested RGB values, separated by commas, as shown in Figure 17.18.

Figure 17.18. The first part of the script prompts the user for the RGB values.


4.
if(c){



If the user entered anything, continue with the code. Otherwise, the value of c will be null, and the bookmarklet ends, as in step 10, below.

5.
s=c.split(',');



Split the entry in c, separated by commas, and put the result into the s array.

6.
for(i=0;i<3;i++){



Loop around the following lines once for each of the three red, green, and blue color values.

7.
n=parseInt(s[i]);



Turn the current element of s into a number, and save it as n.

8.
h+=x.charAt(n>>4)+x.charAt(n&15)}



This line converts n into 2 hexadecimal digits and adds the result to h.

9.
void(prompt('Hexcolor:','#'+h))}



The result (preceded by a pound sign, ready to be copied into an HTML page) is displayed via a prompt command, as shown in Figure 17.19. It's done this way instead of with an alert, so that we can copy the code and paste it later.

Figure 17.19. Another prompt box provides the calculated hex value.


10.
else{void(null);}



If nothing was entered in step 3, step 4 causes the code to jump to this step, where nothing happens.


Previous Page
Next Page