localStorageで保存可能の、シンプルなテーマ切り替え

Ads

Result

ダークモードにも使えるテーマスイッチです。サンプルは簡単なものですがスタイルはCSSで制御しているので応用は効くと思います。

JavaScriptは切り替えとlocalStorageへの保存に利用されています。

javascript

//デフォルト設定
const pressedButtonSelector = '[data-theme][aria-pressed="true"]';
const defaultTheme = 'green';

//buttonにセットしたカスタムデータ属性に準じてテーマ切り替え
const applyTheme = (theme) => {
  const target = document.querySelector(`[data-theme="${theme}"]`);
  document.documentElement.setAttribute("data-selected-theme", theme);
  document.querySelector(pressedButtonSelector).setAttribute('aria-pressed', 'false');
  target.setAttribute('aria-pressed', 'true');
};

const handleThemeSelection = (event) => {
  const target = event.target;
  const isPressed = target.getAttribute('aria-pressed');
  const theme = target.getAttribute('data-theme');        
  
  if(isPressed !== "true") {
    applyTheme(theme);
    localStorage.setItem('selected-theme', theme);
  }
}

//テーマに変更があるかチェックし、変更があればlocalStorageに保存
const setInitialTheme = () => {
  const savedTheme = localStorage.getItem('selected-theme');
  if(savedTheme && savedTheme !== defaultTheme) {
    applyTheme(savedTheme);
  }
};

setInitialTheme();

const themeSwitcher = document.querySelector('.theme-switcher');
const buttons = themeSwitcher.querySelectorAll('button');

buttons.forEach((button) => {
   button.addEventListener('click', handleThemeSelection);
});

css

:root,
[data-selected-theme="green"] {
  --color-background: #A4F3A2;
  --color-text: #034435;
  --color-accent: #00CC66;
}

[data-selected-theme="blue"] {
  --color-background: #55dde0;
  --color-text: #2B4150;
  --color-accent: #00D4E7;
}

[data-selected-theme="pink"] {
  --color-background: #DFB2F4;
  --color-text: #463546;
  --color-accent: #F06EFC;
}

[data-selected-theme="orange"] {
  --color-background: #FA7D61;
  --color-text: #1E1E24;
  --color-accent: #F3601C;
}

設定されたdata-selected-theme属性はhtmlタグに追加されるので、テーマのカスタマイズもしやすいかと思います。

html

<div class="container">
    <h1>テーマ選択</h1>
  <div class="theme-switcher">
    <button data-theme="green" aria-pressed="true">緑</button>
    <button data-theme="blue" aria-pressed="false">青</button>
    <button data-theme="pink" aria-pressed="false">ピンク</button>
    <button data-theme="orange" aria-pressed="false">オレンジ</button>
  </div>

切り替えのスイッチです。

via

以下で詳しく解説されています。
Building an accessible theme picker with HTML, CSS and JavaScript.

タイトルとURLをコピーしました