Convert RGB to Hexadecimal using JavaScript

In one of my previous article, I showed you how to Generate Random RGB Colors using JavaScript. However not all old browsers support the RGB mode. For old browsers, you are safe using Hex values instead of RGB. If you have a RGB value and want to convert it into Hexadecimal mode, here’s how to do it using JavaScript.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Convert RGBtoHEX using JavaScript by DevCurry.com</title>
<script type="text/javascript">
   1:  
   2:         function Rgb() {
   3:             var red = returnHex(200);
   4:             var green = returnHex(255);
   5:             var blue = returnHex(155);
   6:             var hex = "#" + red + green + blue;
   7:                         
   8:             alert(hex);            
   9:         }
  10:  
  11:         // Convert to Hex
  12:         function returnHex(num) {
  13:             // Hex can store 16 different values in 1 character
  14:             if (num == null) return "00";
  15:             num = num.length < 2 ? "0" + num : num
  16:             return num.toString(16);
  17:         }       
  18:     
</script>
</head>
<body onload="randomRgb()">
<div>Demo from DevCurry.com</div>
</body>
</html>

Using the returnHex(num) function, we first check to see if the num is not null, else return 0. We are then using a ternary condition to check if the length of num is less than 2. If it is, prefix ‘0’ to the results, else use the original number. Finally we use toString(16) on the number, to convert it into hexadecimal mode. Remember Hex can store 16 different values in 1 character.

In the Rgb function(), I am passing a sample RBG value and then displaying the converted hex value using alert(). I have not done too many validation checks, in order to keep the example simple and to the point.

On passing 200,255,155 you get #c8ff9b

image






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

4 comments:

Anonymous said...

If you pass 200,14,0 you'll get #c8e00
You need to handle it being a one digit number AFTER converting to base 16, not before.

JavaScript Timer Countdown said...

very cool & good tip, thank you very much for sharing.

RGB to Hex said...

I'm curious as to what the benefit would be of generating random RGB or Hex values? Is there a practical application for this or is this just an exercise of possibilities?

Anonymous said...

Possibly to apply a new background color randomnly or change a theme. Possibilities could be endless