javascripthtmlcolor-picker

How can I make a colorpicker start on picking functionality?


I have a color picker coded with Vue 3 and tailwind

<input id="colorPickerBtn" type="color" class="opacity-0 absolute">

and when I open it, it opens the default browser color picking popup

Image of default color picker dialog

I want it to initialize in color picking functionality (the one highlighted on the screenshot), there's a way to do it (feel free to explain that in regular JS)?


Solution

  • I think you're referring to the eyedropper functionality that is built-in to some browsers. Chrome has some documentation here: https://developer.chrome.com/docs/capabilities/web-apis/eyedropper

    As a warning, it's only supported in the Chrome and Edge browsers. If you wanted to go that route, you might be able to implement it like

    <button id="colorPickerButton">
    
    ...
    
    let chosenColor 
    
    document.getElementById('colorPickerButton').addEventListener('click', (event)=>
        chosenColor = await startEyeDropper()
    })
    async function startEyeDropper() {
        if (('EyeDropper' in window)) {
            const eyeDropper = new EyeDropper();
            try {
              const result = await eyeDropper.open();
              return result.sRGBHex;
            } catch (e) {
              return null;
            }
        } else {
            alert('eyedropper not supported')
        }  
      }
    

    My other thought is since you're already using Vue, you might try using a library like https://www.npmjs.com/package/vue-eye-dropper to implement an eyedropper, which will probably have better cross-browser support anyway.