0

Is there any way to save a DOM manipulated element?

I wrote some basic JavaScript Code, it's checking if the dark mode is on or not.

function systemTheme() {
  var darkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
  if (darkMode === true){
    document.getElementById('headerMainMenu').style.backgroundColor = 'black';
  } else {
    document.getElementById('headerMainMenu').style.backgroundColor = 'white';
  }
}

You can start the function systemTheme with a button.

<div>
      <button onclick="systemTheme()">Click Me</button>
</div>

The problem is: I click the button and the headerMainMenu is black, but when I open another HTML file with an a tag, the color is changing back.

The color is black in the index.html but normal in the about.html. Both are connected to the JavaScript file.

GregGott
  • 95
  • 9
  • 1
    To troubleshoot, first add some console.log() into your code, make sure that the javascript is executed correctly, than check in developer tools window if your #headerMainMenu element is getting it's background changed. – vanowm Jun 17 '21 at 21:36
  • @vanowm I think he's asking if he can keep user events through multiple html files. – Lynel Hudson Jun 17 '21 at 21:37
  • It looks like the `darkMode` value is based on local browser support, so it should be the same on any page. Is it possible to provide a [working demonstration](https://stackoverflow.com/help/minimal-reproducible-example)? – showdev Jun 17 '21 at 21:43
  • Do you mean that you don't want to have to click the button? You can [execute the JavaScript function upon page load](https://stackoverflow.com/questions/807878/how-to-make-javascript-execute-after-page-load) instead. – showdev Jun 17 '21 at 21:46
  • 1
    @devsandbox I'm pretty sure they don't know what they want...I mean the question does not match anything in the issue description...If I had to bet, I'd bet that they want to fix dark mode detection in the about.html, which my guess would be has errors which prevent the javascript execution, or css conflicts. – vanowm Jun 17 '21 at 22:37
  • 1
    I think the question is about how to store data (settings/preferences) across sites. An example of such would be the use of [`window.localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). – Oskar Grosser Jun 17 '21 at 22:56

1 Answers1

0

You need a variable that persists between pages and holds the mode selection. This could be achieved with a session, but the easiest way is a cookie. You would write the mode selected to a cookie in the form:

Document.cookie = "darkMode=true; path=/";

This cookie can then be read on any page in the same domain, as so:

let darkModeForPage = getCookie("darkMode");

The getCookie() function is from https://www.w3schools.com/js/js_cookies.asp

Lew Perren
  • 1,209
  • 1
  • 10
  • 14