life is too short for a diary




Thu 10 Feb 2022

Implementing Dark Mode to Your Jekyll Site without learning CSS

Tags: jekyll

Lots of website have added dark themes to their platform. Twitter also has a dark mode which I really love while reading at night. Also there are benefits of using dark mode for the eyes.

There are lots of tutorials that require adding separte CSS for light and dark theme. However I wanted to leverage a simple javascript solution to implement dark mode.

Create button for light and dark mode

We can use FontAwesome to add moon icon for light mode and sun icon for dark mode.

<a class="dark-mode-button" >
  <i id="icon-dark" class="fa fa-moon"></i>
  <span id="dark-text">Sunset</span>
</a>

Next we need to add darkreader.js to our html file.

<script src="https://cdn.jsdelivr.net/npm/darkreader@4.9.44/darkreader.js"></script>

Toggle between light and dark mode

On clicking the button, we need to call the function darkmode.

document.getElementsByClassName('dark-mode-button')[0].onclick = function() {
    darkmode()
}

The localStorage object allows you to save key/value pairs in the browser. This is useful to save the state of your application between page loads.

function darkmode() {
  let enabled = localStorage.getItem('dark-mode')

  if (enabled === null) {
    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
        enable();
    }
  } else if (enabled === 'true') {
    enable()
  }

  if (localStorage.getItem('dark-mode') === 'false') {
      enable();
  } else {
      disable();
  }
}

Lastly we need to call setFetchMethod to check if the browser is using darkmode before enabling or disabling it.

function enable()  {
  DarkReader.setFetchMethod(window.fetch)
  DarkReader.enable();
  localStorage.setItem('dark-mode', 'true');
}

function disable() {
  DarkReader.disable();
  localStorage.setItem('dark-mode', 'false');
}

Demo


comments powered by Disqus