This script enables a light/dark mode toggle on your website, allowing users to switch between themes seamlessly. The user's preference is saved in localStorage
to persist across sessions.
- Toggle Theme: Switch between light and dark modes using a single button.
- Persistent Theme: Saves the user's theme preference in
localStorage
. - Accessible Icons: Displays sun/moon icons to indicate the current theme.
-
HTML Setup: Add a button with the class
toggle-button
to your HTML.<button class="toggle-button">🌙</button>
-
CSS: Define styles for
.dark-mode
in your CSS..dark-mode { background-color: black; color: white; }
-
JavaScript: Include the script below in your HTML file.
// Light/Dark mode toggle function toggleMode() { const body = document.body; const toggleButton = document.querySelector('.toggle-button'); const isDarkMode = body.classList.toggle('dark-mode'); toggleButton.textContent = isDarkMode ? '☀️' : '🌙'; // Save the mode to localStorage localStorage.setItem('theme', isDarkMode ? 'dark' : 'light'); } // Load the saved theme from localStorage document.addEventListener('DOMContentLoaded', () => { const savedTheme = localStorage.getItem('theme') || 'dark'; // Default to dark const body = document.body; const toggleButton = document.querySelector('.toggle-button'); if (savedTheme === 'dark') { body.classList.add('dark-mode'); toggleButton.textContent = '☀️'; } else { toggleButton.textContent = '🌙'; } });
- Toggle Theme: Click the button to switch themes.
- Automatic Load: The script automatically loads the saved theme when the page is refreshed.
Feel free to fork this project and make improvements. Contributions are welcome!