Let's build a gradient generator using HTML, CSS, and JavaScript!

Let's build a gradient generator using HTML, CSS, and JavaScript!

Build an easy Gradient Generator using HTML, CSS, and JavaScript with just a few lines of code!

·

4 min read

Building a random gradient generator is not as tough as you think you can build one just by writing a few lines of JavaScript, so let's get started with another project.

P.S. I didn't focus much on CSS so ignore the design, also you can find the repository at the bottom of the blog!


Step 1 - Create an index.html file. Create a button with the name 'Generate Gradient' and give it an id of 'gradient-button', next create an input field with a predefined value which consists of linear-gradient of the current page, and make sure you make it readonly also it is hardcoded for now, then give it an id of bg-img-value, and last but not least create a button so that users can copy the gradient color generated.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>Gradient Generator</title>
</head>
<body>

    <main>
        <button id="gradient-button">
            Generate Gradient!
        </button>
        <input 
            id="bg-img-value" 
            type="text" 
            value="background-image: linear-gradient(rgba(10,246,191,1), rgba(5,212,252,1));" 
            readonly>
        <button id="copy-clip">
            Copy to Clipboard
        </button>
    </main>

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

Step 2 - Create a styles.css file and link it in the HTML file. Now let's style out page with some basic CSS.

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap');

* {
    margin: 0;
    padding: 0;
}

body{
    font-family: 'Poppins', sans-serif;
    background-image: linear-gradient(rgba(10,246,191,1), rgba(5,212,252,1));
}

main{
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 1rem;
    overflow: hidden;
}

button{
    cursor: pointer;
    font-size: 1.2rem;
    font-weight: 700;
    padding: 0.8rem 1.1rem;
    border-radius: 6px;
    color: #000;
    background-color: #fff;
    border: 1px solid #000;
}
button:hover{
    transform: scale(1.02);
}
button:active{
    transform: scale(0.98);
}

input{
    font-style: italic;
    font-size: 1.1rem;
    padding: 0.5rem ;
    border-radius: 10px;
    margin: 0 10px;
}

input:focus{
    outline: none;
}

Feel free to customize the page, I didn't wanted to complicate the blog so keeping it simple!


Step 3 - Let's jump on the interesting part now -> JavaScript. Create an index.js file and don't forget to add the script tag at the bottom of HTML file.

Let's get the buttons and input element using 'getElementById' and create a function that generates random color.

const gradientButton = document.getElementById('gradient-button')
const bgImageValue = document.getElementById('bg-img-value')
const copyBtn = document.getElementById('copy-clip')

const getRandomColor = () => {
    let color = '#'
    let letters = '0123456789ABCDEF'

    for(let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)]
    }
    return color
}

Step 4 - Next step is to create a function that uses the getRandomColor function to get two random colors and change the background of the page using linear-gradient, also don't forget to update the value of the input field when the function is called.

const backgroundColor = () => {
    const color1 = getRandomColor()
    const color2 = getRandomColor() 

    document.body.style.backgroundImage = `
        linear-gradient(
            ${color1},${color2}
        )
    `
    bgImageValue.value = `background-image: linear-gradient(${color1}, ${color2})`
}

Step 5 - This is the last function that we create which enables the user to copy the value in the input field on the clipboard.

const copy = () => {
    bgImageValue.select();
    bgImageValue.setSelectionRange(0, 99999)

    document.execCommand("copy")
    alert("Copied to Clipboard!")
}

The setSelectionRange() method sets the start and end positions of the current text selection in an input element.


Step 6 - The last step is the add event listeners on the buttons and call the functions that we created!

gradientButton.addEventListener('click', backgroundColor)
copyBtn.addEventListener('click', copy)

This is the complete JavaScript code below!

const gradientButton = document.getElementById('gradient-button')
const bgImageValue = document.getElementById('bg-img-value')
const copyBtn = document.getElementById('copy-clip')

const getRandomColor = () => {
    let color = '#'
    let letters = '0123456789ABCDEF'

    for(let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)]
    }
    return color
}

const backgroundColor = () => {
    const color1 = getRandomColor()
    const color2 = getRandomColor() 

    document.body.style.backgroundImage = `
        linear-gradient(
            ${color1},${color2}
        )
    `
    bgImageValue.value = `background-image: linear-gradient(${color1}, ${color2})`
}

const copy = () => {
    bgImageValue.select();
    bgImageValue.setSelectionRange(0, 99999)

    document.execCommand("copy")
    alert("Copied to Clipboard!")
}

gradientButton.addEventListener('click', backgroundColor)
copyBtn.addEventListener('click', copy)

Repository of the finished project -> GitHub Repo

Also if you want to do more customization checkout this repository by Eliahu Garcia Lozano -> GitHub Repo

Hope you liked the blog, and if you did make sure you hit those reactions, also follow me here on Hashnode and also on Twitter @Deveshb15 where I post similar content every day!

Did you find this article valuable?

Support Devesh's Blog by becoming a sponsor. Any amount is appreciated!