top of page
Writer's pictureWeb Coding

How to create a random color generator

Learn how to create a random color generator using only HTML, CSS and JavaScript


HTML

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Document</title>
 <link rel="stylesheet" href="style.css">
</head>
<body>
 <p>Color Code: <span id="colorCode"></span></p>
 <button type="button" id="randomColorBtn">Random Color</button>
 <script src="script.js"></script>
</body>
</html>

CSS

*{
 margin0;
 padding0;
}

body{
 min-height100vh;
 displayflex;
 align-itemscenter;
 justify-contentcenter;
 flex-directioncolumn;
 font-size32px;
}

body button{
 font-size24px;
}


JavaScript

let randomColorBtn = document.getElementById('randomColorBtn');
let colorCodeDisplay = document.getElementById('colorCode');
let hexValues = [0123456789"A""B""C""D""E""F"];

randomColorBtn.addEventListener('click'generateColor);

function generateColor(){
 let colorCode = '#';
 for(i = 0i < 6i++){
 let random = Math.floor(Math.random()*hexValues.length);
 colorCode += hexValues[random];
    }

 colorCodeDisplay.innerHTML = colorCode;
 document.body.style.backgroundColor = colorCode;
}

If you found this blog post helpful don’t forget to check out my other projects and if you want more content follow me on


YouTube: https://www.youtube.com/channel/UC2nxqB2usQIS2c8zwVZKWEQ

Instagram: https://www.instagram.com/coding_for_the_web/

Twitter: https://twitter.com/LearnWebCoding


14 views

Comments


bottom of page