The HTML <input type="color" />
element accepts/stores its value in the "#rrggbb
" hexadecimal format. You can convert this hexadecimal value to an RGB value in JavaScript, in the following way:
const inputVal = '#e5e5e5';
const red = parseInt(inputVal.substring(1, 3), 16);
const green = parseInt(inputVal.substring(3, 5), 16);
const blue = parseInt(inputVal.substring(5, 7), 16);
const rgb = [red, green, blue]; // [229, 229, 229]
This works by taking two characters each in the hexadecimal string ("#rrggbb
") for red, green, and blue channels (in an RGB color) respectively, and parsing each value using the Number.parseInt()
method with a radix of 16
.
If you add a "change
" event listener on the input
element and do the conversion in its callback, then you can convert colors of the <input type="color" />
element everytime a new color is picked. For example, consider the following <input type="color" />
element:
<input id="color-picker" type="color" />
You would add the change
event on it (with the Hex to RGB conversion code) in the following way:
const input = document.getElementById('color-picker');
input.addEventListener('change', function (event) {
const inputVal = event.target.value;
const red = parseInt(inputVal.substring(1, 3), 16);
const green = parseInt(inputVal.substring(3, 5), 16);
const blue = parseInt(inputVal.substring(5, 7), 16);
const rgb = [red, green, blue];
console.log(rgb);
// ...
});
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.