Start by creating a new index.html with a linked index.js file like this.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>001 Random Color Generator</title>
</head>
<body>
<script src="index.js"></script>
</body>
</html>
Then, in index.js, let's select an element, declare two functions, and add one event listener.
const body = document.querySelector('body');
This will grab the first <body>
element (we assume there will only be one).
function changeColor() {
body.style.backgroundColor = `rgb(${randomByte()}, ${randomByte()}, ${randomByte()})`;
}
This first function is responsible for manually setting the background color. The DOM element style attribute backgroundColor
is equivalent to the CSS attribute background-color
. We set this to a concatinated string composed of three calls to the same function.
function randomByte() {
return Math.floor((Math.random() * 256));
}
I call this randomByte()
because it will return a value between 0 and 255. The largest byte in decimal notation is 255.
Finally, we will add the event listener on the document.
document.addEventListener('keypress', changeColor);
At this point, your index.js file should look like this, and everything should be functional! You can open up the file on a browser and start pressing keys.
const body = document.querySelector('body');
function changeColor() {
body.style.backgroundColor = `rgb(${randomByte()}, ${randomByte()}, ${randomByte()})`;
}
function randomByte() {
return Math.floor((Math.random() * 256));
}
document.addEventListener('keypress', changeColor)
Now for some modifications. Let's display the color value somewhere on the page. We will add an element and a new function.
Add these elements inside the <body>
above the <script>
.
<h1>Press any key to change the color</h1>
<p id="colorLabel"></p>
By default colorLabel
has no text content. We will create a function that populates its content after ever key press.
const colorLabel = document.getElementById('colorLabel');
function displayColor(c) {
colorLabel.textContent = c;
}
The updated changeColor() function will look like this.
function changeColor() {
const rgbColor = `rgb(${randomByte()}, ${randomByte()}, ${randomByte()})`;
body.style.backgroundColor = rgbColor;
displayColor(rgbColor)
}
Your index.js file should now look like this!
const body = document.querySelector('body');
const colorLabel = document.getElementById('colorLabel');
function displayColor(color) {
colorLabel.textContent = color;
}
function changeColor() {
const rgbColor = `rgb(${randomByte()}, ${randomByte()}, ${randomByte()})`;
body.style.backgroundColor = rgbColor;
displayColor(rgbColor)
}
function randomByte() {
return Math.floor((Math.random() * 256));
}
document.addEventListener('keypress', changeColor)
To see this Javascript snack in action, you can find the source code on CodePen or jsFiddle,
You can also see the source code on GitHub.
Happy Snacking! -🥑