Thursday, August 28, 2025
HomeLanguagesJavascriptHow to create Hex color generator using HTML CSS and JavaScript ?

How to create Hex color generator using HTML CSS and JavaScript ?

Hex color is a six-digit code representing the amount of red, green, and blue that makes up the color. The hex color generator gives the hex code of the selected color.

Approach:

  • To select a color, we will use <input type=”color”> which creates a color picker.
  • Get the value returned by the color picker. (Color picker returns hex value)
  • Set the color as the background and display the hex code.

Example: In this example, we will use the above approach for generating hex color.

HTML




<!DOCTYPE html>
<html>
<head>
    <title>Hex color generator</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            display: grid;
            place-items: center;
            height: 100vh;
            font-size: 20px;
        }    
        .main {
            height: 400px;
            width: 250px;
            background: #3A3A38;
            border-radius: 10px;
            display: grid;
            place-items: center;
            color: #fff;
            font-family: verdana;
            border-radius: 15px;
        }      
        #colorPicker {
            background-color: none;
            outline: none;
            border: none;
            height: 40px;
            width: 60px;
            cursor: pointer;
        }      
        #box {
            outline: none;
            border: 2px solid #333;
            border-radius: 50px;
            height: 40px;
            width: 120px;
            padding: 0 10px;
        }
    </style>
</head>
<body>
    <h1>Hex Color Generator</h1>
    <div class="main">
        <!-- To select the color -->
        Color Picker: <input type="color"
            id="colorPicker" value="#6a5acd">
 
        <!-- To display hex code of the color -->
        Hex Code: <input type="text" id="box">
    </div>
    <script>
        function myColor() {
            // Get the value return by color picker
            var color = document.getElementById('colorPicker').value;
            // Set the color as background
            document.body.style.backgroundColor = color;
 
            // Take the hex code
            document.getElementById('box').value = color;
        }
        // When user clicks over color picker,
        // myColor() function is called
        document.getElementById('colorPicker')
            .addEventListener('input', myColor);
    </script>
</body>
</html>


Output:

RELATED ARTICLES

Most Popular

Dominic
32236 POSTS0 COMMENTS
Milvus
80 POSTS0 COMMENTS
Nango Kala
6609 POSTS0 COMMENTS
Nicole Veronica
11779 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11828 POSTS0 COMMENTS
Shaida Kate Naidoo
6719 POSTS0 COMMENTS
Ted Musemwa
7002 POSTS0 COMMENTS
Thapelo Manthata
6678 POSTS0 COMMENTS
Umr Jansen
6690 POSTS0 COMMENTS