Wednesday, 29 March, 2023 UTC


Summary

Javascript has an Eyedropper API for selecting colors.
The process for creating an eyedropper color picker is pretty straightforward:
const eyeDropper = new EyeDropper();

eyeDropper
    .open()
    .then((result) => alert("Selected color: " + result.sRGBHex))
The open() method of the EyeDropper object will return a promise waiting for the user to click on a color.
The returned result just contains the sRGBHex property that we will use to show the selected color.
And the interesting part is that you can select colors also from outside the browser window.
Testing for the support of the Javascript API eyedropper
Currently the Eyedropper API [only works] in Chrome, Edge, and Opera. No support yet in Firefox in Safari.
So, be a sure test for the browser support of this feature before using it:
const supportEyedropAPI = () => ('EyeDropper' in window)

const openEyedrop = ()=> {
  if (!supportEyedropAPI()) {
    return alert("EyeDropper API not supported")
  }

  const eyeDropper = new EyeDropper();
  // rest of the code here
}
Closing the Javascript eyedropper with AbortController
By default, the eyedropper tool will be closed when the user hits the ESC key.
If you want to have programmatic control over when the eyedropper is closed you can use the Javascript AbortController interface.
const eyeDropper = new EyeDropper();
const abortController = new AbortController();
// use abortController.abort() to programmatically close the eyeDropper

eyeDropper
    .open({ signal: abortController.signal })
    .then((result) => alert("Selected color: " + result.sRGBHex))
Handling errors with the catch() method
If you cancel the selection before picking a color you may get the below error:
AbortError: Failed to execute 'open' on 'EyeDropper': The user canceled the selection.
We can use the promise catch() method to handle this message (and other errors as well) :
eyeDropper
    .open({ signal: abortController.signal })
    .then((result) => { //... })
    .catch((err) => { // log or take action on err})
Checkout here the full codepen used in this Javascript eyedropper example. Happy coding!
The post How to create an eyedropper color selector tool with vanilla Javascript appeared first on Js Craft.