Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   Помогите доделать смену темы с сохранением в localStorage (https://javascript.ru/forum/dom-window/85156-pomogite-dodelat-smenu-temy-s-sokhraneniem-v-localstorage.html)

WebMachine 24.04.2023 04:46

Помогите доделать смену темы с сохранением в localStorage
 
В общем есть: https://jsfiddle.net/Georka/dkqpmbzr/1/

Как сделать так чтобы помимо фона в localStorage ещё и сохранялся текст кнопки. Остальное всё как есть оставить..

Только нужно решение в стиле Vanilla js
Без всяких подключений Нео из матрицы. Only simple code

рони 24.04.2023 05:10

смена темы с сохранением в localStorage
 
WebMachine,
желательно размещать код здесь или в другой песочнице.
<!DOCTYPE HTML>
<html>

<head>
    <title>Untitled</title>
    <meta charset="utf-8">
    <style type="text/css">
        body {
            color: #222;
            background-color: #fff;
        }

        body.dark-theme {
            color: #eee;
            background-color: #121212;
        }

        body.dark-theme a {
            color: #809fff;
        }

        .btn-toggle:after {
            content: "Dark Theme"
        }

        body.dark-theme .btn-toggle:after {
            content: "Light Theme"
        }
    </style>
    <script>
        document.addEventListener("DOMContentLoaded", () => {
            const btn = document.querySelector(".btn-toggle");
            let currentTheme = localStorage.getItem("theme");
            if (currentTheme == "dark") {
                document.body.classList.add("dark-theme");
            }
            btn.addEventListener("click", function(event) {
                document.body.classList.toggle("dark-theme");
                currentTheme = currentTheme == "dark" ? "light" : "dark";
                localStorage.setItem("theme", currentTheme);
            });
        })
    </script>
</head>

<body>
    <button class="btn-toggle" type="button"></button>
</body>

</html>

WebMachine 25.04.2023 05:31

спасибо Рони)


Часовой пояс GMT +3, время: 11:10.