JavaScript Nibbles 001: Random Color Generator

by jvon1904

HTML

<!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>
  <h1>Press any key to change the color</h1>
  <p id="colorLabel"></p>
  <script src="index.js"></script>
</body>
</html>

JavaScript

const body = document.getElementsByTagName('body').item(0);
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)