Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

How to open a color picker (eyedropper) using JavaScript

Programming Bytes

Overview

We can use the interface to initiate the eyedropper tool to select a color code from the screen.

Creating a new object for the EyeDropper interface will get a new EyeDropper instance. The EyeDropper interface contains an open method that will open the eyedropper. This method returns a promise. That occurs when the user selects a color from the screen.

We can check if our browser supports EyeDropper by checking if the window.EyeDropper property is defined.

Example

The code below demonstrates how to use the EyeDropper interface to pick a color from the screen.

Console
EyeDropper Example

Explanation

  • Line 5: We create a button element.
  • Line 7: We create a variable btn for the Eyedropper execution.
  • Line 8: We check if the EyeDropper interface is supported in the browser by checking if the window.EyeDropper property is defined.
  • Line 12: We add the click event listener to the btn.
  • Line 13: When the user clicks the button, we create a new EyeDropper object and invoke the open method. This method will open the eyedropper tool. This method returns a promise which is resolved when the user selects a color. The details of the chosen color are available when we resolve the promise.
  • We press "Escape" to close the opened eyedropper.

Note: The EyeDropper interface is available only in secure contexts (HTTPS). Because it’s still in the experimental phase, please refer to browser support here.

RELATED TAGS

javascript
RELATED COURSES

View all Courses

Keep Exploring