DEV Community

Cory LaViska
Cory LaViska

Posted on • Edited on • Originally published at abeautifulsite.net

10 7

Exploring the EyeDropper API

The EyeDropper API has landed in Chrome and Edge 95! This is a simple promise-based API that lets you select a color from anywhere on the screen. Let's dive in and see how it works.

To start, we'll add a button that activates the eye dropper.

<button type="button">Select a color</button>
Enter fullscreen mode Exit fullscreen mode

When the button is clicked, we'll launch the eye dropper. As soon as the user selects a color, we'll update the page's background to match.

const button = document.querySelector('button');

if ('EyeDropper' in window) {
  const eyeDropper = new EyeDropper();

  button.addEventListener('click', () => {
    eyeDropper
      .open()
      .then(colorSelectionResult => {
        document.body.style.backgroundColor = colorSelectionResult.sRGBHex;
      })
      .catch(() => {
        // The user canceled selection
      });
  });
} else {
  // The EyeDropper API isn't supported
}
Enter fullscreen mode Exit fullscreen mode

Breaking it down

Here's what's happening in the code above:

  1. Feature-detect the API
  2. Instantiate an EyeDropper object
  3. Listen for button clicks
  4. Call the eye dropper's open() method, which returns a Promise
  5. Wait for the promise to resolve (the user selected a color) or reject (the user canceled selection)
  6. On resolve, grab the hex value and set the background
  7. On reject, do nothing (the empty catch will prevent an error hitting the console)

Note how I'm feature-detecting the EyeDropper API. This is important because, at the time of this writing, Firefox and Safari don't support it. That doesn't mean you can't use the API to progressively enhance your users' experience, though!

For example, I'm using it in Shoelace's color picker to show an eye dropper if the API is available. Otherwise, I don't show the eye dropper but everything else still works.

Another Example

I whipped up another example that's a bit more practical. Play around with it and let me know what you think!

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay