Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change <input type=color> value onChange

Good day!

I am trying to get a user to pick a color and when they pick a color, I want to change the value to the color they want. I assumed it would be a boostrap feature since this is from bootstrap, but unfortunately, it would have to be modified and customize manually. Is there a way I can change the value when the user picks the color of their choice.

As of now, I have an onChange=alert to notify user of the color they have chosen, but I want to avoid using alerts and have the value change on behind the user input.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I hope I did my best to explain my issue and I hope to learn from this!

Thank you!

<input type="color" class="form-control form-control-color" id="colorPicker" value="#000002" onchange="alert(this.value);" />

>Solution :

  • Don’t use inline on* handlers. JS should be in one place only ant that’s its respective tag or file. Use Element.addEventListener() instead
  • Create a function to handle your color change and place the logic inside of it
  • Get the selected color inside your function from the Event currentTarget.value
// Cache your elements
const elColorPicker = document.querySelector("#colorPicker");
const elColorCode = document.querySelector("#colorCode");
const elBody = document.querySelector("body");



// Change color function
const changeColor = (evt) => {
  const selectedColor = evt.currentTarget.value;
  elColorCode.value = selectedColor;
  elBody.style.backgroundColor = selectedColor;
};

// Add the Event to your input
elColorPicker.addEventListener("input", changeColor);
<input type="color" class="form-control form-control-color" id="colorPicker" value="#000002">
<input readonly type="text" class="form-control form-control-color" id="colorCode" value="#000002">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading