1

On my index page, when I click a button the page background turns to black but not on the other pages, even if I link the .js file to all html documents. How do I make it so that the background turns black to all pages on a button click.

Here is what I've got so far

function myFunction() {
  document.getElementsByTagName("body")[0].style.cssText = "background: black;"
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
    <style>
      body {
        background: white;
       }
      </style>
</head>
<body>
    <button id="button" onclick="myFunction()">Change to black</button>
    
    
</body>
</html>
  • You'll need to store that the background should be black in either a cookie or `localStorage` that will then be read when each page loads. Also, [`document.getElementsByTagName("body")[0]` is a very bad idea](https://stackoverflow.com/questions/54952088/how-to-modify-style-to-html-elements-styled-externally-with-css-using-js/54952474#54952474). All you need there is `document.body` – Scott Marcus Jul 25 '22 at 15:55

1 Answers1

1

You could save the background color in localStorage and read it upon page load. Whenever you navigate to another page of your site - which loads that script - it will read the stored value and change the background color accordingly.

Script (customize.js):

function setBGColor() {
  var bgColor = localStorage.getItem("bgColor");
  document.body.style.backgroundColor = bgColor;
}

function changeBGColor(newColor) {
  localStorage.setItem("bgColor", newColor);
  setBGColor();
}

setBGColor();

In your HTML:

...
<body>
    <button id="button" onclick="changeBGColor('black')">Change to black</button>
</body>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71