Skip to content Skip to sidebar Skip to footer

Using The Css Of Previous Page And Apply To Current Page

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

Solution 1:

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 valuevar 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 functionfunctiontoggleNightMode() {
  var currentMode = localStorage.getItem('nightMode');
  if(!currentMode) {
    //the vaeriable is not set, set it to default valuelocalStorage.setItem("nightMode", "OFF");
  }
  elseif(currentMode == "ON") {
    //current mode is ON, now set it to OFFlocalStorage.setItem("nightMode", "OFF");
  }
  else {
    //set to ONlocalStorage.setItem("nightMode", "ON");
  }
}

Solution 2:

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?

Post a Comment for "Using The Css Of Previous Page And Apply To Current Page"