DEV Community 👩‍💻👨‍💻

Cory LaViska
Cory LaViska

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

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!

Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!