Skip to content

Instantly share code, notes, and snippets.

@dongminkim
Created October 3, 2012 18:25
Show Gist options
  • Select an option

  • Save dongminkim/3828798 to your computer and use it in GitHub Desktop.

Select an option

Save dongminkim/3828798 to your computer and use it in GitHub Desktop.
Color Converter (Hex and RGB)
<html>
<head>
<title>Color Converter</title>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<style>
div {margin:10px;}
</style>
</head>
<body>
<div id="colorDisplay" style='float:left; width:200px; height:200px;'>
</div>
<div style='float:left'>
Hex: <input id="rgbHex" type="text" maxlength="7" tabindex="1">
<hr>
Red: <input class='rgb' id="rgbRed" tabindex="2" type="text" maxlength="3"><br>
Green: <input class='rgb' id="rgbGreen" tabindex="3" type="text" maxlength="3"><br>
Blue: <input class='rgb' id="rgbBlue" tabindex="4" type="text" maxlength="3"><br>
</div>
<script>
var hexFocused = 1;
function updateColor()
{
var hex = '#' + $('#rgbHex').val();
$('#colorDisplay').css('backgroundColor', hex);
}
function hexChanged()
{
var hex = $('#rgbHex').val();
if (hex.substr(0, 1) == '#') {
hex = hex.substr(1);
$('#rgbHex').val(hex);
return;
}
var red = parseInt(hex.substr(0, 2), 16);
var green = parseInt(hex.substr(2, 2), 16);
var blue = parseInt(hex.substr(4, 2), 16);
$('#rgbRed').val(red);
$('#rgbGreen').val(green);
$('#rgbBlue').val(blue);
updateColor();
}
function rgbChanged()
{
var red = parseInt($('#rgbRed').val());
var green = parseInt($('#rgbGreen').val());
var blue = parseInt($('#rgbBlue').val());
var hex = decimalToHex(red, 2) + decimalToHex(green, 2) + decimalToHex(blue, 2);
$('#rgbHex').val(hex);
updateColor();
}
function decimalToHex(decimal, padding) {
var hex = parseInt(decimal).toString(16);
while (hex.length < padding)
hex = "0"+hex;
return hex;
}
$('#rgbHex').change(hexChanged).focus(function() { hexFocused = 1; });
$('.rgb').change(rgbChanged).focus(function() { hexFocused = 0; });
$(function () { $('#rgbHex').focus() });
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment