Minimalist Dark Mode Solution – lightDarkTheme

Category: Color , Javascript | July 13, 2024
AuthorMECHALABS-LLC
Last UpdateJuly 13, 2024
LicenseMIT
Views50 views
Minimalist Dark Mode Solution – lightDarkTheme

lightdarktheme is a minimalist dark mode solution for web developers.

It uses JavaScript to implement dark mode on web pages and saves user theme preferences in the browser’s local storage. This allows the selected theme to apply automatically on subsequent visits.

How to use it:

1. Add the following JS snippet to your webpage. The JavaScript code listens for the DOM content to load and then finds the theme toggle button and the body element. The code checks localStorage for a saved theme and applies it if found.

document.addEventListener('DOMContentLoaded', function() {
    const themeToggleBtn = document.getElementById('theme-toggle');
    const body = document.body;
    // Load the saved theme from localStorage
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
        body.classList.add(savedTheme);
    }
    themeToggleBtn.addEventListener('click', function() {
        if (body.classList.contains('dark-theme')) {
            body.classList.remove('dark-theme');
            body.classList.add('light-theme');
            localStorage.setItem('theme', 'light-theme');
        } else {
            body.classList.remove('light-theme');
            body.classList.add('dark-theme');
            localStorage.setItem('theme', 'dark-theme');
        }
    });
});

2. Create a toggle button to switch between light and dark modes.

<button id="theme-toggle">Switch Theme</button>

3. Define your CSS styles for light and dark modes. That’s it.

.light-theme {
  background-color: #fafaf7;
  color: #222222;
}
.dark-theme {
  background-color: #2222222;
  color: #fafaf7;
}

See Also:

You Might Be Interested In:


Leave a Reply