Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add predefined colors to <input type="color">?

According to MDN, the list attribute can be used for <input> elements of type color to provide a list of predefined colors. That page also indicates that list is supported at least in Chrome.

Though when I specified some colors they were not shown as expected using Chrome 67. Instead, only empty items were shown in the color picker popup and clicking on them set the value of the input to rgba(0, 0, 0, 0).

Predefined colors for <input type="color"> not shown in Chrome

Simple example:

<input type="color" list="presetColors">
<datalist id="presetColors">
  <option value="#ff0000"/>
  <option value="#00ff00"/>
  <option value="#0000ff"/>
</datalist>

I tried to specify the colors in different formats like used in CSS, e.g. rgb() or color keywords like red, though none of them worked.

Having a look at the HTML specification, it says that the input only accepts "lowercase simple colors", which is defined as the 6-character hex format.

So, is that a bug in Chrome or am I supposed to specify the colors in a different format?

like image 472
Sebastian Zartner Avatar asked Jun 18 '18 11:06

Sebastian Zartner


2 Answers

Use this format for list:

 <input type="color" list="presetColors">
  <datalist id="presetColors">
    <option>#ff0000</option>/>
    <option>#00ff00</option>
    <option>#0000ff</option>
  </datalist>

Demo: http://jsfiddle.net/lotusgodkk/GCu2D/4045/

Note: As mentioned, this works only in chrome now.

like image 156
K K Avatar answered Oct 13 '22 01:10

K K


For color type, the options datalist suggests the recommended color on the swatch palette. Must be in hexadecimal format

Please check this, hope this will help you :)

 <h3>input[type="color""] with &lt;datalist></h3>
            <p>For <code>color</code> type, the options  <code>datalist</code> suggests the recommended color on the swatch palette. Must be in hexadecimal format</p>
            <input type="color" id="color" value="#ee0000" list="reds" />
            
            <datalist id="reds">
              <option>#ff0000</option>
              <option>#cc0000</option>
              <option>#990000</option>
              <option>#660000</option>
              <option>#330000</option>
              <option>red</option> <!--ignored as invalid -->
              <option>#F00</option> <!--ignored as invalid -->
            </datalist>
<h3>Quirks</h3>
<p>Notice the different look of the color picker when no <code>list</code> attribute is included:</p>
<input type="color" id="color2" value="#ee0000" /> - no list attribute
<br/>
<input type="color" id="color3" value="#ee0000" list /> -presence of list attribute, but no list
like image 35
Jagjeet Singh Avatar answered Oct 12 '22 23:10

Jagjeet Singh