JavaScript file that changes the background color of a webpage randomly

JavaScript file that changes the background color of a webpage randomly when a button is clicked. Here’s the code:

// Get a reference to the button element
const changeColorButton = document.getElementById('changeColorButton');

// Function to generate a random color
function getRandomColor() {
  const letters = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

// Function to change the background color
function changeBackgroundColor() {
  const randomColor = getRandomColor();
  document.body.style.backgroundColor = randomColor;
}

// Add a click event listener to the button
changeColorButton.addEventListener('click', changeBackgroundColor);




To use this code, you’ll need to have an HTML file with a button element with the id “changeColorButton” on your webpage. Here’s a simple HTML file to go along with the JavaScript code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Random Background Color Change</title>
</head>
<body>
    <button id="changeColorButton">Change Background Color</button>
    <script src="random-background.js"></script>
</body>
</html>


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *