How to create Hex color generator using HTML CSS and JavaScript?
Last Updated :
25 Jul, 2024
Hex color codes are six-digit combinations representing the amount of red, green, and blue (RGB) in a color. These codes are essential in web design and development for specifying colors in HTML and CSS. The hex color generator provides the hex code for any selected color, making it a valuable tool for designers and developers.
Approach to Generating Hex Colors
To generate hex colors, we will use the <input type="color"> HTML element, which creates a user-friendly color picker. This tool allows users to select a color and returns its hex value. Here’s a step-by-step approach:
- Create a Color Picker: Use the <input type="color"> element to enable users to pick a color from the palette.
- Retrieve the Hex Value: Get the hex value returned by the color picker.
- Display the Hex Code: Set the selected color as the background and display its corresponding 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:
Generating hex colors using the <input type="color"> element is a straightforward and effective approach. This method simplifies the process for designers and developers, allowing them to easily obtain and use hex color codes in their projects.
How to create Hex color generator using HTML CSS and JavaScript ?
Explore
JavaScript Basics
Array & String
Function & Object
OOP
Asynchronous JavaScript
Exception Handling
DOM
Advanced Topics