Помогите сохранить цвет Body в LocaleStorage

Помогите сохранить цвет Body и состояние кнопки в LocaleStorage. Чтобы после перезагрузки страницы цвет Body и положение переключателя сохранялись.

Есть такой переключатель:

<div class="toggle">
     <input class="input-theme" type="checkbox" id="toggle" />
     <label for="toggle"></label>
</div>

Его стили:

.toggle {
  display: flex;
  align-items: center;
  transform: translate3d(10%, 0%, 0);
  &:before {
    content: 'DARK';
    font-size: 12px;
    color: #fff;
  }

  &:after {
    content: 'LIGHT';
    font-size: 12px;
    color: #fd1015;
  }

  label {
    position: relative;
    display: inline-block;
    width: 30px;
    height: 30px;
    margin: 0 10px;
    background-color: #fd1015;
    box-shadow: inset 0 0 2px 1px rgba(0, 0, 0, 0.1), 0px 0px 10px 1px #ef4247;
    border-radius: 50px;
    cursor: pointer;

    &:before {
      content: '';
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      transition: width 0.2s cubic-bezier(0, -1.85, 0.27, 1.75);
      height: 20px;
      width: 20px;
      background-color: #fd0f14;
      border-radius: 50%;
      box-shadow: inset 0px 0px 0px 3px #fff;
    }
  }

  .input-theme {
    position: relative;
    display: none;
    &:checked + label {
      background-color: #57de72;
      box-shadow: inset 0 0 2px 1px rgba(0, 0, 0, 0.1),
        0px 0px 10px 6px rgba(3, 132, 28, 0.5411764705882353);

      &:before {
        width: 2px;
        background-color: #fff;
      }
    }
  }
}

.on {
  background-color: #fff;
  .toggle {
    &:before {
      color: #fd1015;
    }
    &:after {
      color: #fff;
    }
  }
}

Слушатель:

toggle.addEventListener('change', () =>
  document.body.classList.toggle('on')
);

Цвет переключает, но не выходит сохранить состояние фона и кнопки в локал сторэдж.


Ответы (1 шт):

Автор решения: Daniil Loban

Что касается работы с localStoage то информацию по нему также можно найти на сайте MDN Веб-технологии для разработчиков > Интерфейсы > веб API > Storage

Что касается тем, то можно поискать статьи, видео, а можно изучить сам сайт MDN хотя бы потому что на нем применяется множество стандартов (сайт написан на React ) код выглядит так:

window.localStorage.setItem("theme", theme); 

Как видно все согласно документации. Этот код содержится в функции которая вызывается из обработчика переключателя тем (по событию onclick элемента ThemeButton):

export function switchTheme(theme: string, set: (theme: string) => void) {
  const html = document.documentElement;

  if (window && html) {
    html.className = theme;
    html.style.backgroundColor = "";
    try {
      window.localStorage.setItem("theme", theme);
    } catch (err) {
      console.warn("Unable to write theme to localStorage", err);
    }
    set(theme);
    postToIEx(theme);
  }
}

Как видно они делают еще несколько проверок, если переписать это на ванильный JS:

/*  
  Функция вызываемая из обработчкика переключения темы
  Параметры:
    theme - строкака "dark" , "light"  и т.п.
    setTheme - функция для сохранения темы в `state` программы 
*/
function switchTheme(theme, setTheme) {
  const html = document.documentElement;
  if (window && html) { 
    html.className = theme;           // записываем клас в html 
    html.style.backgroundColor = "";  // убираем цвет бакграунда
    try {
      window.localStorage.setItem("theme", theme); // cохраняем в localStorage
    } catch (err) {
      console.warn("не удалось сохранить theme в localStorage", err);
    }
    // сохраняем тему в текущем состоянии приложения (React, useState)
    setTheme(theme); // чтобы брать значение из переменной а не атрибута элемента
  }
}

В результате:

введите сюда описание изображения

→ Ссылка