Last active
October 24, 2023 06:57
-
-
Save amberlex78/532d9f95b3584f344b9d06fb8b4be0e6 to your computer and use it in GitHub Desktop.
dark-light switcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(() => { | |
'use strict'; | |
// Функция для работы с localStorage | |
const getStoredValue = (key, defaultValue) => localStorage.getItem(key) || defaultValue; | |
const setStoredValue = (key, value) => localStorage.setItem(key, value); | |
// Функции для установки фронт-темы и фронт-иконки | |
const setFrontTheme = theme => document.documentElement.setAttribute('data-bs-theme', theme); | |
const setFrontThemeIcon = themeIcon => document.querySelector('#themeIcon').setAttribute('xlink:href', themeIcon); | |
// Установка начальных значений | |
setFrontTheme(getStoredValue('theme', 'light')); | |
setFrontThemeIcon(getStoredValue('themeIcon', '#icoMoonFill')); | |
// Функция для обновления темы и иконки | |
const updateTheme = () => { | |
const currentTheme = getStoredValue('theme', 'light'); | |
const newTheme = currentTheme === 'light' ? 'dark' : 'light'; | |
setStoredValue('theme', newTheme); | |
setFrontTheme(newTheme); | |
const currentThemeIcon = getStoredValue('themeIcon', '#icoMoonFill'); | |
const newThemeIcon = currentThemeIcon === '#icoMoonFill' ? '#icoSunFill' : '#icoMoonFill'; | |
setStoredValue('themeIcon', newThemeIcon); | |
setFrontThemeIcon(newThemeIcon); | |
}; | |
// Добавление обработчика события | |
document.querySelector('.change-theme').addEventListener('click', updateTheme); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment