aboutsummaryrefslogtreecommitdiff
path: root/layouts/partials/header/theme-button.html
blob: 0a8313b30eaba3810a040d8ca4c9189aecff13cc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

<button class="toggle-theme" aria-label="Toggle Theme" title="Toggle Theme" onclick="toggleTheme()">
  <span class="theme-icon light"> {{ partial "utils/icon" "sun" }} </span>
  <span class="theme-icon dark"> {{ partial "utils/icon" "moon" }} </span>
</button>

<script>
  document.addEventListener('DOMContentLoaded', function () {
    const theme = localStorage.getItem('theme');

    if (!theme || theme === 'light') {
      setTheme('light');
    } else {
      setTheme(theme);
    }
  });

  function setTheme(theme) {
    const html = document.querySelector('html');
    localStorage.setItem('theme', theme);

    if (theme === 'light') {
      if (html.classList.contains('dark')) {
        document.querySelector('html').classList.remove('dark');
      }

      document.querySelector('.theme-icon.light').style.display = 'none';
      document.querySelector('.theme-icon.dark').style.display = 'block';
    } else {
      if (!html.classList.contains('dark')) {
        document.querySelector('html').classList.add('dark');
      }

      document.querySelector('.theme-icon.dark').style.display = 'none';
      document.querySelector('.theme-icon.light').style.display = 'block';
    }
  }

  function toggleTheme() {
    const theme = localStorage.getItem('theme');

    if (theme === 'light') {
      setTheme('dark');
    } else {
      setTheme('light');
    }
  }
</script>