Created
July 3, 2023 02:14
-
-
Save rg3915/ae0b920323407d6a2fefa2afb2db4153 to your computer and use it in GitHub Desktop.
dark mode switcher
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
<html class=""> | |
<head> | |
<!-- A diferença é que o JS precisa ser carregado antes. --> | |
<script src="{% static 'js/switcher.js' %}"></script> | |
</head> | |
<body> | |
<div id="switcher" class="dark-mode-switcher cursor-pointer shadow-md fixed bottom-0 right-0 box dark:bg-dark-2 border rounded-full w-40 h-12 flex items-center justify-center z-50 mb-10 mr-10"> | |
<!-- classes do TailwindCSS --> | |
<div class="mr-4 text-gray-700 dark:text-gray-300">Dark Mode</div> | |
<div class="dark-mode-switcher__toggle border"></div> | |
</div> | |
</body> | |
</html> |
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
const html = document.getElementsByTagName('html')[0] | |
const theme = localStorage.getItem('theme') | |
if (theme) { | |
html.classList.add(theme) | |
} else { | |
// Set the default theme if no preference is found in localStorage | |
html.classList.add('light') | |
} | |
window.addEventListener('load', () => { | |
const switcher = document.getElementById('switcher') | |
switcher.addEventListener('click', function() { | |
// Toggle the light and dark classes on the element | |
html.classList.toggle('light') | |
html.classList.toggle('dark') | |
// Update the theme preference in localStorage | |
if (html.classList.contains('light')) { | |
localStorage.setItem('theme', 'light') | |
} else { | |
localStorage.setItem('theme', 'dark') | |
} | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment