Please review the code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>RGB to HEX (and vice versa) converter</title>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.0/normalize.min.css">
<style>
body{
color: #222;
font-family: "Segoe UI", sans-serif;
}
#main {
margin: 10% auto;
max-width: 300px;
}
input[type="text"] {
padding: 10px;
width: 100%;
outline: 0;
border: 0;
border-bottom: 1px dashed;
background: inherit;
text-shadow: 0 1px 0 #f0f0f0;
font-size: 18px;
}
::-webkit-input-placeholder { color: #a9a9a9; }
:-moz-placeholder { color: #a9a9a9; }
::-moz-placeholder { color: #a9a9a9; }
:-ms-input-placeholder { color: #a9a9a9;}
</style>
</head>
<body>
<div id="main">
<p><input id="rgb" type="text" placeholder="rgb(255, 255, 255)"></p>
<p><input id="hex" type="text" placeholder="#ffffff"></p>
</div>
<script>
(function() {
"use strict";
var inputRgb = document.getElementById("rgb"),
inputHex = document.getElementById("hex"),
converter = {
// help: http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
toHex: function() {
function componentToHex(c) {
var hex = parseInt(c).toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
var rgb = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/.exec(inputRgb.value);
inputHex.value = rgb ? "#" + componentToHex(rgb[1]) + componentToHex(rgb[2]) + componentToHex(rgb[3]) : "";
converter.changeBgColor(inputRgb.value);
},
toRgb: function() {
// expand shorthand form (e.g. "03f") to full form (e.g. "0033ff")
var hex = inputHex.value.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, function(m, r, g, b) {
return r + r + g + g + b + b;
}),
result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
inputRgb.value = result ? "rgb(" + [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)].join(", ") + ")" : "";
converter.changeBgColor(inputHex.value);
},
changeBgColor: function(color) {
document.body.style.backgroundColor = color;
}
};
inputRgb.addEventListener("input", converter.toHex, false);
inputHex.addEventListener("input", converter.toRgb, false);
}());
</script>
</body>
</html>
Jsbin - http://jsbin.com/fokayomo/1/