← Back to all tutorials

How to a create a color picker with Tailwind CSS and JavaScript

a color picker
Published and written on Jul 25 2024 by Michael Andreuzza

Today we will be creating a color picker using Tailwind CSS and JavaScript. super fun!

What are color pickers?

A color picker is a tool that allows users to select a color from a predefined set of colors. It is commonly used in design software, web development, and graphic design applications.

Use Cases:

  • Web design: A color picker is used to select colors for web design projects, such as websites, logos, and user interfaces.
  • Graphic design: A color picker is used to select colors for graphic design projects, such as logos, icons, and illustrations.
  • Design software: A color picker is used in design software, such as Figma, Sketch and Penpot, to select colors for design projects.
  • Photo editing software: A color picker is used in photo editing software, such as Adobe Photoshop and GIMP, to select colors for photo editing projects.

and many more!

Let’s get started with the markp

The markp is a simple color picker that allows users to select a color from a predefined set of colors.

  • ìd="colorSwatches": This is a div element that will hold the color swatches.
  • ìd="selectedColor": This is a div element that will hold the selected color.
  • ìd="colorCode": This is a span element that will hold the color code.
  • ìd="copyButton": This is a button element that will copy the color code to the clipboard.
<div>
  <div id="colorSwatches"></div>
  <div id="selectedColor"></div>
  <div>
    <span id="colorCode"></span>
    <button id="copyButton"> Copy </button>
  </div>
</div>

Now, we write the script

We’ll be using the document.getElementById() method to select the elements we want to work with.

  • colors: This is an array of objects that contains the name and hex value of each color.
const colors = [{
        name: "yellow",
        hex: "#f6c760"
    },
    {
        name: "ambar",
        hex: "#F59E0B"
    },
    {
        name: "orange",
        hex: "#F97316"
    },
    {
        name: "red",
        hex: "#df4f43"
    },
    {
        name: "pink",
        hex: "#ed7eb2"
    },
    {
        name: "green",
        hex: "#50b18a"
    },
    {
        name: "blue",
        hex: "#86cded"
    },
    {
        name: "indigo",
        hex: "#725bf6"
    },
];
  • colorSwatches: This is a reference to the colorSwatches element.
  • selectedColor: This is a reference to the selectedColor element.
  • colorCode: This is a reference to the colorCode element.
  • copyButton: This is a reference to the copyButton element.
  • colors.forEach(): This is a loop that iterates over the colors array and creates a new div element for each color.
  • swatch.style.backgroundColor: This is a property that sets the background color of the div element to the hex value of the color.

Rendering the color swatches

Now that we have the markup and the script, let’s render the color swatches.

  • colors.forEach(): This is a loop that iterates over the colors array and creates a new div element for each color.
  • const swatch = document.createElement("div");: This is a new div element that will be used to create the color swatches.
  • swatch.className = "size-8 rounded-full cursor-pointer";: This is a property that sets the class name of the div element to “size-8 rounded-full cursor-pointer”.
  • swatch.style.backgroundColor = hex;: This is a property that sets the background color of the div element to the hex value of the color.
  • swatch.addEventListener("click", () => selectColor(hex));: This is a property that adds a click event listener to the div element.
  • colorSwatches.appendChild(swatch);: This is a method that appends the div element to the colorSwatches element.
colors.forEach(({
    hex
}) => {
    const swatch = document.createElement("div");
    swatch.className = "size-8 rounded-full cursor-pointer";
    swatch.style.backgroundColor = hex;
    swatch.addEventListener("click", () => selectColor(hex));
    colorSwatches.appendChild(swatch);
});

Selecting the color

Now that we have the color swatches, we need to select the color when the user clicks on it.

  • fucntion selectColor(hex): This is a function that takes a hex value as an argument and sets the background color of the selectedColor element to the hex value.
  • selectedColor.style.backgroundColor = hex;: This is a property that sets the background color of the selectedColor element to the hex value.
  • colorCode.textContent = hex;: This is a property that sets the text content of the colorCode element to the hex value.
function selectColor(hex) {
    selectedColor.style.backgroundColor = hex;
    colorCode.textContent = hex;
}

Copying the color code to the clipboard

Now that we have the selected color, we need to copy the color code to the clipboard. We’ll use the navigator.clipboard API for this.

  • copyButton.addEventListener("click", () => {}): This is a property that adds a click event listener to the copyButton element. When the user clicks on the button, the function inside the parentheses will be executed.
  • const textToCopy = colorCode.textContent;: This is a property that sets the textToCopy variable to the text content of the colorCode element.
  • navigator.clipboard.writeText(textToCopy): This is a method that writes the textToCopy variable to the clipboard.
  • alert("Color code copied to clipboard!");: This is a method that displays an alert message with the text “Color code copied to clipboard!”.
  • console.log("Copied text:", textToCopy);: This is a method that logs the text “Copied text:” and the textToCopy variable to the console.
  • .catch((err) => { console.error("Failed to copy: ", err); });: This is a method that logs the text “Failed to copy: ” and the error message to the console.
copyButton.addEventListener("click", () => {
    const textToCopy = colorCode.textContent;
    navigator.clipboard
        .writeText(textToCopy)
        .then(() => {
            alert("Color code copied to clipboard!");
            console.log("Copied text:", textToCopy);
        })
        .catch((err) => {
            console.error("Failed to copy: ", err);
        });
});

Selecting the first color

  • selectColor(colors[0].hex);: This is a method that selects the first color in the colors array.

The full markup

const colors = [{
        name: "yellow",
        hex: "#f6c760"
    },
    {
        name: "ambar",
        hex: "#F59E0B"
    },
    {
        name: "orange",
        hex: "#F97316"
    },
    {
        name: "red",
        hex: "#df4f43"
    },
    {
        name: "pink",
        hex: "#ed7eb2"
    },
    {
        name: "green",
        hex: "#50b18a"
    },
    {
        name: "blue",
        hex: "#86cded"
    },
    {
        name: "indigo",
        hex: "#725bf6"
    },
];
const colorSwatches = document.getElementById("colorSwatches");
const selectedColor = document.getElementById("selectedColor");
const colorCode = document.getElementById("colorCode");
const copyButton = document.getElementById("copyButton");
colors.forEach(({
    hex
}) => {
    const swatch = document.createElement("div");
    swatch.className = "size-8 rounded-full cursor-pointer";
    swatch.style.backgroundColor = hex;
    swatch.addEventListener("click", () => selectColor(hex));
    colorSwatches.appendChild(swatch);
});

function selectColor(hex) {
    selectedColor.style.backgroundColor = hex;
    colorCode.textContent = hex;
}
copyButton.addEventListener("click", () => {
    const textToCopy = colorCode.textContent;
    navigator.clipboard
        .writeText(textToCopy)
        .then(() => {
            alert("Color code copied to clipboard!");
            console.log("Copied text:", textToCopy);
        })
        .catch((err) => {
            console.error("Failed to copy: ", err);
        });
});
// Initialize with the first color
selectColor(colors[0].hex);

Conclusion

This is a simple color picker that demonstrates how to use Tailwind CSS and JavaScript to create a color picker with a predefined set of colors. It’s a great starting point for building more complex color pickers and color pickers with more features. Remember to add validation and error handling to make sure the color picker is always up-to-date, accurate, secure and accessible.

Hope you enjoyed this tutorial and have a great day!

/Michael Andreuzza

Did you like this tutorial? Please share it with your friends!

Reviews and opinions

Get lifetime access to every theme available today for $199 and own them forever. Plus, new themes, lifetime updates, use on unlimited projects and enjoy lifetime support.

No subscription required!

Lexington

Beautifully designed HTML, Astro.js and Tailwind themes! Save months of time and build your startup landing page in minutes.