Skip to content

Instantly share code, notes, and snippets.

@rg3915
Created July 3, 2023 02:14
Show Gist options
  • Save rg3915/ae0b920323407d6a2fefa2afb2db4153 to your computer and use it in GitHub Desktop.
Save rg3915/ae0b920323407d6a2fefa2afb2db4153 to your computer and use it in GitHub Desktop.
dark mode switcher
<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>
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