About this snippet

Implement a user-friendly dark mode toggle for your website using CSS custom properties (variables) and a simple JavaScript switcher for persistence.

Size
1.6 KB
Uses
HTML, CSS, JavaScript
Loads
Nothing external
Views
382
<button id="darkModeToggle">Toggle Dark/Light Mode</button>
<div class="content-area">
  <h2>Sample Heading</h2>
  <p>This is some sample content that will change its appearance based on the selected theme. Try toggling the mode!</p>
</div>
:root {
  --bg-color: #ffffff;
  --text-color: #333333;
  --content-bg: #f4f4f4;
  --button-bg: #e0e0e0;
  --button-text: #333333;
}

[data-theme="dark"] {
  --bg-color: #333333;
  --text-color: #ffffff;
  --content-bg: #444444;
  --button-bg: #555555;
  --button-text: #ffffff;
}

body {
  background-color: var(--bg-color);
  color: var(--text-color);
  font-family: sans-serif;
  transition: background-color 0.3s, color 0.3s;
  padding: 20px;
}

.content-area {
  background-color: var(--content-bg);
  padding: 20px;
  margin-top: 20px;
  border-radius: 5px;
  transition: background-color 0.3s;
}

#darkModeToggle {
  padding: 10px 15px;
  background-color: var(--button-bg);
  color: var(--button-text);
  border: 1px solid var(--text-color);
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s, color 0.3s;
}
const toggleButton = document.getElementById('darkModeToggle');
const currentTheme = localStorage.getItem('theme');

if (currentTheme) {
    document.documentElement.setAttribute('data-theme', currentTheme);
}

toggleButton.addEventListener('click', () => {
    let theme = document.documentElement.getAttribute('data-theme');
    if (theme === 'dark') {
        document.documentElement.removeAttribute('data-theme');
        localStorage.removeItem('theme');
    } else {
        document.documentElement.setAttribute('data-theme', 'dark');
        localStorage.setItem('theme', 'dark');
    }
});
Esc
↑↓ moveEnter select

Start from a template

Open an .html file, or HTML, CSS, JS, Markdown, Less or TypeScript files. You can also drop them here. Styles and scripts go into their panes.

Share

Source

Keyboard shortcuts

Save