How to Create Color Picker in Javascript and HTML

In this tutorial, you will learn how to create color picker in javascript and HTML. I will not say this is something that you are going to create from scratch. We already have an element that offers the functionality of a color picker.

As you already know that input element can be of different types such as text, number, email, etc.  One of those types is color.  If you set the type of an input element to color, then that input element will act as a color picker and this is something that we are going to cover in this tutorial.

In the following example, we have created a color picker using an input element. As soon as we pick the color, we will change the color of the text in the h1 element as well as change the background color of our web page.  Please have a look over the code example and the steps given below.

HTML & CSS

  • We have 3 elements in the HTML file (div, input, and h1). The div element is just a wrapper for the rest of the elements.
  • We are using style attribute with div element to center align all the elements horizontally.
  • We have 2 input elements. In the first input element, we will display the hex value of the color. The second input element will act as a color picker.
  • The innerText for the h1 element is “Hello World”.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div style="text-align: center">
        <input type="text" id="hex">
        <input type="color" id="color">
        <h1>Hello World</h1>
    </div>

    <script src="script.js"></script>
</body>
</html>

Javascript

  • We have selected both the input elements using the document.querySelector() method and stored them in the colorInput and hexInput variables respectively.
  • We have attached the input event listener to the color picker.
  • In the event handler function, we are getting value from the color picker and assigning it to the color variable.
  • The color variable holds a hex value of the color and we are displaying it in the hexInput using the value property.
  • We are changing the backgroundColor of the body element to the picked color.
  • We are also changing the color of the text in the h1 element to the picked color.
let colorInput = document.querySelector('#color');
let hexInput = document.querySelector('#hex');

colorInput.addEventListener('input', () =>{
    let color = colorInput.value;
    hexInput.value = color;
    // document.body.style.backgroundColor = color;

    document.querySelector('h1').style.color = color;
});