scrimba
JS color tool
Convert RGB Color To Hex - Challenge Requirements
Go Pro!Bootcamp

Bootcamp

Study group

Collaborate with peers in your dedicated #study-group channel.

Code reviews

Submit projects for review using the /review command in your #code-reviews channel

To see this lesson you need to be logged in. Joining Scrimba is free and gives you access to 20+ courses.Sign up
Convert RGB Color To Hex - Challenge Requirements
AboutCommentsNotes
Convert RGB Color To Hex - Challenge Requirements
Expand for more info
index.js
run
preview
console
const hexInput = document.getElementById('hexInput');
const inputColor = document.getElementById('inputColor');

hexInput.addEventListener('keyup', () => {

const hex = hexInput.value;
if(!isValidHex(hex)) return;

const strippedHex = hex.replace('#', '');

inputColor.style.backgroundColor = "#" + strippedHex;
})

const isValidHex = (hex) => {
if(!hex) return false;

const strippedHex = hex.replace('#', '');
return strippedHex.length === 3 || strippedHex.length === 6;
}

//Create a function to convert Hex to RGB
//this should work with 3 or 6 character hex values
//Hint - use parseInt("", 16) to convert a hex value to a decimal value
//should return an object with 3 properties - r,g, and b
//Test your function with a few different use cases

const convertHexToRGB = (hex) => {
if(!isValidHex(hex)) return null;

let strippedHex = hex.replace('#','');

if(strippedHex.length === 3) {
strippedHex = strippedHex[0] + strippedHex[0]
+ strippedHex[1] + strippedHex[1]
+ strippedHex[2] + strippedHex[2];
}

const r = parseInt(strippedHex.substring(0,2), 16);
const g = parseInt(strippedHex.substring(2,4), 16);
const b = parseInt(strippedHex.substring(4,6), 16);

return {r,g,b}
}

Console
{r:
255
, g:
255
, b:
238
}
,
/index.html
-2:35