Search code examples
javascriptcolor-picker

Color Picker Created in Javascript not rendering color values to DOM


I have the following function, it is called from another function used to create a simple div. The select element gets rendered to the DOM and the option and color input elements are all present but for some reason setting the value on the color input does not seem to work. I have outputted the values of "col.value" both before and after assignment and they each output the correct value, but when i render it, all options appear blank and there seems to be no value set on the input object. Here is the code

const colourSelector = () => {
            let sel = document.createElement("select");
            let cols = {
                "red":"#ff0000",
                "blue":"#0000ff",
                "green":"#33cc33",
                "orange":"#ff9900",
                "purple":"#800080",
                "brown":"#996633",
                "yellow":"#ffff00",
            };
            for(key in cols) {
                let opt = document.createElement('option');
                opt.value = key;
                let col = document.createElement('input');
                col.type = "color";
                col.value = cols[key];
                opt.appendChild(col);
                console.log(opt);
                sel.appendChild(opt);
            }
            return sel;
        }

And here is a sample

output


Solution

  • I think you would like something like this:

        const colourSelector = () => {
            let sel = document.createElement("select");
            let cols = {
              "red":"#ff0000",
              "blue":"#0000ff",
              "green":"#33cc33",
              "orange":"#ff9900",
              "purple":"#800080",
              "brown":"#996633",
              "yellow":"#ffff00",
            };
            for(key in cols) {
              let opt = document.createElement('option');
              opt.value = key;
              opt.style.backgroundColor = cols[key];
              sel.appendChild(opt);
            }
            return sel;
        }
    
        document.body.appendChild(colourSelector());