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.
1. | javascript:var s,i,n,h='', Start off the bookmarklet by initializing four variables . |
2. | The variable x is set to the valid hexadecimal values. |
3. | This line prompts the user for the requested RGB values, separated by commas, as shown in Figure 17.18 . |
4. | 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. | Split the entry in c , separated by commas, and put the result into the s array. |
6. | Loop around the following lines once for each of the three red, green, and blue color values. |
7. | 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. |
10. | If nothing was entered in step 3, step 4 causes the code to jump to this step, where nothing happens. |