Canofeggs 5410
Canofeggs 5410

Reputation: 39

How to make a JavaScript code that changes the site's layout apply to all pages?

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>

Upvotes: 1

Views: 238

Answers (1)

Robbe Vermandel
Robbe Vermandel

Reputation: 178

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>

Upvotes: 1

Related Questions