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
, andh1
). Thediv
element is just a wrapper for the rest of the elements. - We are using
style
attribute withdiv
element to center align all the elements horizontally. - We have 2
input
elements. In the firstinput
element, we will display the hex value of the color. The secondinput
element will act as a color picker. - The
innerText
for theh1
element is“Hello World”
. - We have also included our javascript file
script.js
with ascript
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 thedocument.querySelector()
method and stored them in thecolorInput
andhexInput
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 thehexInput
using thevalue
property. - We are changing the
backgroundColor
of thebody
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; });