Native color selection in HTML with the input type=color

For the past few days, I've been coding a tool for some theme customization and needed a simple way to allow users to select their colors.

It seems that you can build an HTML natural color selector by using the color input.

<input type="color" />

You can set it to default stating color by using the value attribute. And you can also use the same attribute to read the selected value in that input.

<input type="color" value="#ff0000" id="color-input" />
<script type="application/javascript">
    const selectedColor = document.getElementById("color-main").value;
    console.log(document.getElementById("color-main").value);
</script>

The color will be returned in a hex format (eq: #f00211), the default being #000000.

From a Javascript perspective, we can use the input and change events to track the first selection and any changes in the color input.

colorPicker.addEventListener("input", updateFirst, false);
colorPicker.addEventListener("change", watchColorPicker, false);

Below is a small working codepen for it:

See the Pen
by JS Craft (@js-craft)
on
CodePen.

You can read more about the color input in this article on developer.mozilla.org.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X