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>
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
}
Breaking it down #
Here's what's happening in the code above:
- Feature-detect the API
- Instantiate an EyeDropper object
- Listen for button clicks
- Call the eye dropper's
open()
method, which returns a Promise - Wait for the promise to resolve (the user selected a color) or reject (the user canceled selection)
- On resolve, grab the hex value and set the background
- 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!