0

I want to implement a night mode on my website and I have created that css. The problem that I'm having is that when I move to another page it uses the general css file.

I use some javascript to switch to the night mode css. How do I ensure that the night mode css is applied to all pages when activated and when I switch to the general css it applies to all?

iPreach
  • 13
  • 1
  • 1
  • 3
  • you will Need to send an query string paramter like /yourpath?nightmode=true and on the other page you get the params and with an JavaScript Code you switch it again – bill.gates Oct 12 '19 at 21:26

2 Answers2

2

You could use a cookie or localStorage variable for that. In this example, I am using a localStorage variable called nightMode, and I set it to either "ON" or "OFF". The correct CSS file is loaded based on the value of the variable.

Note that a localStorage variable is a variable saved in the browser without an expiry date, so this variable will stay saved in the browser even after the window is closed and re-opened.

//on page load, check localStorage value
var stylesheet = document.createElement('link');
stylesheet.rel = "stylesheet";
  

if(localStorage.getItem('nightMode') == "ON") {
  //add link to night mode CSS
  stylesheet.href = "path/to/nightmode.css";
  document.getElementsByTagName('head')[0].appendChild(stylesheet);
}
else {
  //add link to night mode CSS
  link.href = "path/to/normalmode.css";
  document.getElementsByTagName('head')[0].appendChild(stylesheet);
}

//set the nightmode at some point by calling this function
function toggleNightMode() {
  var currentMode = localStorage.getItem('nightMode');
  if(!currentMode) {
    //the vaeriable is not set, set it to default value
    localStorage.setItem("nightMode", "OFF");
  }
  else if(currentMode == "ON") {
    //current mode is ON, now set it to OFF
    localStorage.setItem("nightMode", "OFF");
  }
  else {
    //set to ON
    localStorage.setItem("nightMode", "ON");
  }
}
Anis R.
  • 6,656
  • 2
  • 15
  • 37
0

You will Need to add query Parameters to your url like /yourUrl?night=true. On the other side you Need to read the Parameters out of the url and execute an JavaScript function that switch your css to nightmode.

Here is post how to get the params out of the URL: How can I get query string values in JavaScript?

bill.gates
  • 14,145
  • 3
  • 19
  • 47