« Back to Index

[website day/night theme switcher with cookies]

View original Gist on GitHub

Tags: #js #javascript #cookies

themes.css

/* 
the normal css (not shown) is standard 'day' mode stylings.
we simply add a .night class to override the styles to 'night' mode.
*/

.night {
  background: #263238;
}

.night .title, .night h1, .night h2, .night h3, .night h4, .night h5, .night h6,
.night a, .night a:visited {
  color: #fff;
}

body.night, .night button, .night input, .night select, .night textarea,
.night .main-menu a:hover, .night .social-menu a:hover,
.night a:active, .night a:focus, .night a:hover{
  color: #ccc;
}

.night blockquote strong,
.night td > code,
.night h1 > code,
.night h2 > code,
.night h3 > code,
.night h4 > code,
.night h5 > code,
.night h6 > code,
.night li > code,
.night a > code,
.night p > code,
.night li strong {
  color: #ff6ed0;
}

website day and night theme switcher with cookies.js

var menu = document.getElementsByClassName("main-menu")[0];
var anchors = menu.getElementsByTagName("a");
var trigger;

// search menu for button that has #theme id attribute
// this is a button we've explicitly added to the HTML for theme switching
// ideally you'd generate this button in JS instead
// for some reason I didn't do that, no reason, I was just lazy ¯\_(ツ)_/¯
for (var i = 0; i < anchors.length; i++) {
  a = anchors[i];
  if (a.href.indexOf("#theme") >= 0) {
    trigger = a;
  }
}

// check if we already have a 'theme' cookie set
theme = document.cookie.match("theme=([^;]+)");

// if we do have a cookie, then trigger the right theme based on its current value
// this code block is executed as the page loads
// note: switching between theme modes is otherwise manually handled by the user clicking theme button
if (theme) {
  mode = theme[1];
  
  // check if we're in 'night' mode and switch to 'day' mode
  if (mode == "night") {
    document.body.classList.add("night");
    document.body.classList.remove("day");
    trigger.innerText = "Day Mode";
  }

  // check if we're in 'day' mode and switch to 'night' mode
  if (mode == "day") {
    document.body.classList.add("day");
    document.body.classList.remove("night");
    trigger.innerText = "Night Mode";
  }
}

// this function sets 'theme' cookie and switches theme
function themeSwitch(e) {
  if (e.target.href.indexOf("#theme") >= 0) {
    document.body.classList.toggle("night");

    if (document.body.classList.contains("night")) {
      e.target.innerText = "Day Mode";
      document.cookie = "theme=night;domain=.integralist.co.uk;path=/";
    } else {
      e.target.innerText = "Night Mode";
      document.cookie = "theme=day;domain=.integralist.co.uk;path=/";
    }
  }
}

var menu = document.getElementById("navmenu");

// allow the user to click the 'theme switcher' button to change the theme
menu.addEventListener("click", themeSwitch);