DannyMC01
DannyMC01

Reputation: 11

CSS Stylesheet Switching via adding cookies

Code I'm using, works great but it doesn't stick when navigating around the site - because it needs to trigger a cookie - is there a way to do that? Here's the entire code I'm using:

<!DOCTYPE html>
<html>
<head>
<link id="pagestyle" rel="stylesheet" type="text/css" href="default.css">
<script>
function swapStyleSheet(sheet){
    document.getElementById('pagestyle').setAttribute('href', sheet);
}
</script>
</head>
<body>
<h2>Javascript Change StyleSheet Without Page Reload</h2>
<button onclick="swapStyleSheet('dark.css')">Dark Style Sheet</button>
<button onclick="swapStyleSheet('blue.css')">Blue Style Sheet</button>
<button onclick="swapStyleSheet('default.css')">Default Style Sheet</button>
</body>
</html>

Upvotes: 1

Views: 793

Answers (1)

Liftoff
Liftoff

Reputation: 25372

Nathaniel is correct in his comment that JS executes after the page is loaded, so you'll see a noticeable flicker if you apply the style after page load.

However, for the sake of answering your question, you can get/set a cookie with some pretty simple javascript.

function setCookie(name, value, days)
{
  var d = new Date();
  d.setTime(d.getTime() + days * 24 * 60 * 60 * 1000);
  document.cookie = name + "=" + value + "; expires=" + d.toUTCString() + "; path=/";
}

function getCookie(name)
{
  var cookies = document.cookie.split(";");
  for(var i = 0; i < cookies.length; i++)
  {
    var ck = cookies[i].trim().split("=");
    if(ck[0] == name)
      return ck[1];
  }
  
  return false;
}


Here's an example with your code:

window.onload = function(){
  var viewmode = getCookie("viewmode");
  if(viewmode)
    document.getElementById('pagestyle').setAttribute('href', viewmode);
}

function swapStyleSheet(sheet){
  document.getElementById('pagestyle').setAttribute('href', sheet);
  setCookie("viewmode", sheet, 30);
}

function setCookie(name, value, days)
{
  var d = new Date();
  d.setTime(d.getTime() + days * 24 * 60 * 60 * 1000);
  document.cookie = name + "=" + value + "; expires=" + d.toUTCString() + "; path=/";
}

function getCookie(name)
{
  var cookies = document.cookie.split(";");
  for(var i = 0; i < cookies.length; i++)
  {
    var ck = cookies[i].trim().split("=");
    if(ck[0] == name)
      return ck[1];
  }
  
  return false;
}
<!DOCTYPE html>
<html>
<head>
<link id="pagestyle" rel="stylesheet" type="text/css" href="default.css">
</head>
<body>
<h2>Javascript Change StyleSheet Without Page Reload</h2>
<button onclick="swapStyleSheet('dark.css')">Dark Style Sheet</button>
<button onclick="swapStyleSheet('blue.css')">Blue Style Sheet</button>
<button onclick="swapStyleSheet('default.css')">Default Style Sheet</button>
</body>
</html>

Upvotes: 1

Related Questions