How to open a color picker (eyedropper) using JavaScript
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.
Explanation
- Line 5: We create a
buttonelement. - Line 7: We create a variable
btnfor the Eyedropper execution. - Line 8: We check if the
EyeDropperinterface is supported in the browser by checking if thewindow.EyeDropperproperty 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
EyeDropperobject and invoke theopenmethod. 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
EyeDropperinterface is available only in secure contexts (HTTPS). Because it’s still in the experimental phase, please refer to browser support here.