Skip to content

Instantly share code, notes, and snippets.

@davidsword
Created October 16, 2019 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidsword/3dfea4fe9a25e63a1f710662a847c968 to your computer and use it in GitHub Desktop.
Save davidsword/3dfea4fe9a25e63a1f710662a847c968 to your computer and use it in GitHub Desktop.
Toggle Darkmode w/ a body class
<a href='#' data-darkmode-btn>Toggle Darkmode</a>
<script type="text/javascript">
/* eslint-disable */
var darkModeBtn = document.querySelector('a[data-darkmode-btn]');
var bodyEle = document.querySelector('body');
if (localStorage.getItem('darkmode') === 'yes') {
bodyEle.classList.add("darkmode");
}
function darkmodetoggle(e) {
e.preventDefault();
var darkmode = localStorage.getItem('darkmode');
if (darkmode === "yes") {
bodyEle.classList.remove("darkmode");
localStorage.setItem('darkmode', 'no');
} else {
bodyEle.classList.add("darkmode");
localStorage.setItem('darkmode', 'yes');
}
return;
}
darkModeBtn.addEventListener('click', darkmodetoggle);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment