|
| 1 | +/* eslint-env browser */ |
1 | 2 | ;(function () { |
2 | | - 'use strict' |
| 3 | + 'use strict'; |
3 | 4 |
|
4 | | - var currentTheme = localStorage.getItem('theme') || 'light' |
5 | | - document.documentElement.setAttribute('data-theme', currentTheme) |
| 5 | + const storage = (typeof window !== 'undefined' && window.localStorage) ? window.localStorage : null; |
| 6 | + const currentTheme = storage ? (storage.getItem('theme') || 'light') : 'light'; |
| 7 | + document.documentElement.setAttribute('data-theme', currentTheme); |
6 | 8 |
|
7 | | - function bind() { |
8 | | - var toggle = document.querySelector('.night-mode-toggle') |
9 | | - if (!toggle) return |
10 | | - toggle.addEventListener('click', function () { |
11 | | - var next = document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark' |
12 | | - document.documentElement.setAttribute('data-theme', next) |
13 | | - localStorage.setItem('theme', next) |
14 | | - }) |
| 9 | + function bind () { |
| 10 | + const toggle = document.querySelector('.night-mode-toggle'); |
| 11 | + if (!toggle) return; |
| 12 | + toggle.addEventListener('click', function (e) { |
| 13 | + e.preventDefault(); |
| 14 | + const next = document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark'; |
| 15 | + document.documentElement.setAttribute('data-theme', next); |
| 16 | + if (storage) storage.setItem('theme', next); |
| 17 | + }); |
15 | 18 | } |
16 | 19 |
|
17 | | - // Ensure the button exists before binding |
18 | 20 | if (document.readyState === 'loading') { |
19 | | - document.addEventListener('DOMContentLoaded', bind) |
| 21 | + document.addEventListener('DOMContentLoaded', bind); |
20 | 22 | } else { |
21 | | - bind() |
| 23 | + bind(); |
22 | 24 | } |
23 | | -})() |
| 25 | +})(); |
0 commit comments