Last active
August 2, 2021 14:18
-
-
Save syntaxlexx/4276892ca3fb91f4869ff2d487e472ca to your computer and use it in GitHub Desktop.
Toggle Dark Mode and Light Mode Automatically or Manually
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="absolute top-0 left-0"> | |
<div class="p-5" id="theme-toggler"> | |
<i class="mdi mdi-lightbulb-on-outline mdi-24px"></i> | |
</div> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
document.addEventListener("DOMContentLoaded", function(event) { | |
function toggleDarkMode() { | |
if(document.querySelector('html').classList.contains("dark")) | |
enableDarkMode(false) | |
else | |
enableDarkMode(true) | |
} | |
function enableDarkMode(status = true) { | |
if(status) | |
document.querySelector('html').classList.add('dark') | |
else | |
document.querySelector('html').classList.remove('dark') | |
} | |
// auto themer | |
function autoThemer() { | |
var nightTimes = [7,18]; // between 7am and 6pm | |
var currentHour = new Date().getHours(); | |
if(currentHour <= nightTimes[0] || currentHour >= nightTimes[1]) { | |
// enable dark mode | |
enableDarkMode(); | |
} | |
} | |
autoThemer(); | |
document.getElementById('theme-toggler').addEventListener('click', function() { | |
toggleDarkMode(); | |
}, false); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment