Skip to content

Instantly share code, notes, and snippets.

@codingwithsara
Created November 8, 2018 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codingwithsara/c6128443fdae53732d8f0d9414e99eaa to your computer and use it in GitHub Desktop.
Save codingwithsara/c6128443fdae53732d8f0d9414e99eaa to your computer and use it in GitHub Desktop.
How to Create RGB to HEX Converter with JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>RGB to HEX Converter</title>
<link href="https://fonts.googleapis.com/css?family=Inconsolata" rel="stylesheet">
<style>
#container {
font-family: 'Inconsolata', monospace;
text-align: center;
width: 800px;
margin: 160px auto;
}
table {
width: 100%;
}
h1 {
margin-top: 100px;
font-size: 38px;
}
input[type="range"] {
width: 200px;
height: 50px;
}
</style>
<script>
function changeRange() {
// Get R,G,B values & Convert string into integer.
var r = parseInt(document.getElementById("r").value);
var g = parseInt(document.getElementById("g").value);
var b = parseInt(document.getElementById("b").value);
// Generate color. Example: #20b9ff
var color = "#" + hex(r) + hex(g) + hex(b);
// Change background color and text.
document.body.style.backgroundColor = color;
document.getElementById("hex-label").innerText = color;
document.getElementById("r-label").innerText = r;
document.getElementById("g-label").innerText = g;
document.getElementById("b-label").innerText = b;
if (r < 100 && g < 100 && b < 100) {
document.getElementById("container").style.color = "white";
} else {
document.getElementById("container").style.color = "black";
}
}
function hex(v) {
// Get hexadecimal numbers.
var hex = v.toString(16);
if (v < 16) {
hex = "0" + hex;
}
return hex;
}
</script>
</head>
<body>
<div id="container">
<table>
<tr>
<th>Red</th>
<th>Green</th>
<th>Blue</th>
</tr>
<tr>
<td><input type="range" min="0" max="255" value="255" id="r" onchange="changeRange()"></td>
<td><input type="range" min="0" max="255" value="255" id="g" onchange="changeRange()"></td>
<td><input type="range" min="0" max="255" value="255" id="b" onchange="changeRange()"></td>
</tr>
<tr>
<td id="r-label">255</td>
<td id="g-label">255</td>
<td id="b-label">255</td>
</tr>
</table>
<h1 id="hex-label">#ffffff</h1>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment