简体   繁体   中英

Cant change the background color of entire page with the click of a button

I was trying to change the color of body section with the click of a button with id="btn" . but when I launch the index.html the background color is not changing. if any one has the solution please i want the concept behind the solution.

HTML code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Document</title>
  </head>
  <body>
    <div class="butn">
      <button type="button" id="btn">Click to change baackground</button>
    </div>
    <style src="main.js"></style>
  </body>
</html>

CSS :

body {
  margin: 0;
  height: 100%;
  text-align: center;
  background-color: white;
}

.butn {
  margin-top: 15%;
  display: inline-block;
}

button {
  height: 5rem;
  width: 15rem;

  border: none;
  border-radius: 0.5rem;
}

JS code:

var color = [
  "AntiqueWhite",
  "CadetBlue",
  "BurlyWood",
  "Crimson",
  "DarkSlateBlue",
  "LightGoldenRodYellow",
  "LightCyan",
];
var randomNumber = Math.round(Math.random() * 6);
document.getElementById("btn").addEventListener("click", function () {
  changeBackground();
});

function changeBackground() {
  console.log(color[randomNumber]);
  document.body.style.backgroundColor = color[randomNumber];
}

Firstly, your js file should be in script tag and not in style tag.

Secondly, random number is getting generated only once when your js file loads, instead move random number inside the changeBackground function, so that it can get a new number every time the button is clicked

As the randomNumber variable is outside the function, it only gets initialized once.
So you have to move the randomNumber to the function to generate random color every time you click on the button.

js

function changeBackground() {
    var randomNumber = Math.round(Math.random() * 6);
    console.log(color[randomNumber]);

    document.body.style.backgroundColor = color[randomNumber];
  }

And while including js file, you should write in this manner

<script src="main.js"></script>

You must put var randomNumber = Math.round(Math.random() * 6); inside the function changeBackground, otherwise it will only get this number once. This way, it gets a new number each time this function is called.

function changeBackground() {
    var randomNumber = Math.round(Math.random() * 6);
  console.log(color[randomNumber]);
  document.body.style.backgroundColor = color[randomNumber];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM