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 Hex12: function returnHex(num) {13: // Hex can store 16 different values in 1 character14: if (num == null) return "00";15: num = num.length < 2 ? "0" + num : num16: 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
Tweet
4 comments:
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.
very cool & good tip, thank you very much for sharing.
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?
Possibly to apply a new background color randomnly or change a theme. Possibilities could be endless
Post a Comment