Ying Ying
Ying Ying

Reputation: 35

How can i get the RGB values from color picker and display them?

I am totally new to html and javascript. I have made a color picker and it displays the hex value. But I want it to display and save the rgb values as well. How to do it, anyone can help me. Thanks!

This is my html

<td>Background Colour:</td>
  <td id="colorControls">
    <input type="color" id="colorChangeBG">
    <p>RGB:<span id="HexValue">"0, 0, 0"</span></p>
    </td>
  <td>-</td>

This is my javascript

var colorChange;
var initialColor = "#ffffff";

window.addEventListener("load", changemycolor);       
   
function changemycolor() {
    colorChange = document.querySelector("#colorChangeBG");
    colorChange.value = initialColor;
    colorChange.addEventListener("input", update);
}          

function update(event) {
  box.style.background = event.target.value;
  document.getElementById('HexValue').innerHTML = event.target.value;
}

Upvotes: 1

Views: 4411

Answers (1)

GMKHussain
GMKHussain

Reputation: 4709

Try this, event change as you want

let colorChangeBG = document.getElementById("colorChangeBG").value;
let HexValue =  document.getElementById("HexValue");

function hexTorgb(hex) {
  return ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0];
}


function getRGBColor(that){
 let thatv = that.value; 
 let rgbV = hexTorgb(thatv);
 
 console.log(thatv)
 console.log(rgbV);
 
 HexValue.innerHTML = rgbV;
}
<td>Background Colour:</td>
  <td id="colorControls">
    <input type="color" id="colorChangeBG" onchange="getRGBColor(this)">
    <p>RGB:<span id="HexValue">"0, 0, 0"</span></p>
    </td>
  <td>-</td>

Upvotes: 2

Related Questions