Javascript HEX to RGB Converter

Web Design & Web Development

Demo

Sponsored links

 

Code

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>HEX to RGB Converter</title>
    <link rel="stylesheet" type="text/css" href="https://demo.plantpot.works/assets/css/normalize.css">
    <link rel="stylesheet" href="https://use.typekit.net/opg3wle.css">
    <link rel="stylesheet" type="text/css" href="style.css">
  </head>
  <body>
    <div id="container">
      <div class="box">
        <div class="color-code">#
          <input id="hex" class="hex" type="text" maxlength="6" placeholder="Enter Colorcode">
        </div>
        <button id="convert" class="button">Convert to RGB</button>
        <div class="rgb">
          rgb(
          <div id="red"></div>,
          <div id="green"></div>,
          <div id="blue"></div>
          )
        </div>
      </div>
    </div>
    <script src="converter.js"></script>
  </body>
</html>

CSS

@charset "utf-8";
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
html {
  font-size: 16px;
}
body {
  background-color: #e7e7e7;
  font-family: futura-pt, sans-serif;
  -webkit-tap-highlight-color: rgba(0,0,0,0);
}
#container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  padding: 10px;
}
.box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  max-width: 280px;
}
.color-code {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  border-bottom: solid 1px #3d3935;
  font-size: 1.5rem;
}
.hex {
  width: 60%;
  padding-left: 10px;
  border: none;
  border-radius: 0;
  background: none;
  outline: none;
}
.rgb {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 0 10px;
  font-size: 1.5rem;
}
.button {
  width: 100%;
  margin: 20px 0;
  padding: 10px;
  border: none;
  border-radius: 4px;
  background-color: #000;
  color: #fff;
  font-size: 1.25rem;
  outline: none;
  cursor: pointer;
}

Javascript

var redEl = document.getElementById('red');
var greenEl = document.getElementById('green');
var blueEl = document.getElementById('blue');
var convert = document.getElementById('convert');
var hexEl = document.getElementById('hex');

convert.addEventListener('click', () => {
  var hexVal = hexEl.value;

  if(hexVal.length == 3) {
    hexVal = hexVal.slice(0,1) + hexVal.slice(0,1) + hexVal.slice(1,2) + hexVal.slice(1,2) + hexVal.slice(2,3) + hexVal.slice(2,3);
  }

  redEl.innerHTML = parseInt(hexVal.slice(0,2), 16);
  greenEl.innerHTML = parseInt(hexVal.slice(2,4), 16);
  blueEl.innerHTML = parseInt(hexVal.slice(4,6), 16);
});