-
Notifications
You must be signed in to change notification settings - Fork 0
/
theme-toggle.js
27 lines (25 loc) · 1.05 KB
/
theme-toggle.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Function to toggle between dark and light theme
function toggleTheme() {
const body = document.body;
const currentTheme = localStorage.getItem('theme');
if (currentTheme === 'dark') {
body.classList.replace('dark-theme', 'light-theme');
localStorage.setItem('theme', 'light');
document.dispatchEvent(new CustomEvent('themeChange', { detail: { theme: 'light' } }));
} else {
body.classList.replace('light-theme', 'dark-theme');
localStorage.setItem('theme', 'dark');
document.dispatchEvent(new CustomEvent('themeChange', { detail: { theme: 'dark' } }));
}
}
// Event listener for the theme toggle button
document.getElementById('theme-toggle').addEventListener('click', toggleTheme);
// Check local storage for theme preference and apply it
document.addEventListener('DOMContentLoaded', () => {
const savedTheme = localStorage.getItem('theme');
if (savedTheme === 'dark') {
document.body.classList.add('dark-theme');
} else {
document.body.classList.add('light-theme');
}
});