summaryrefslogtreecommitdiffstats
path: root/themes/danix-xyz-hacker/assets/js/theme-toggle.js
blob: bb95b2afca4226a65c8e699bed8415490ac14802 (plain)
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
48
49
50
51
52
53
document.addEventListener('DOMContentLoaded', function() {
  const themeToggle = document.getElementById('theme-toggle');
  const sunIcon = document.getElementById('theme-icon-sun');
  const moonIcon = document.getElementById('theme-icon-moon');

  function updateThemeIcon() {
    const isDark = document.documentElement.classList.contains('theme-dark');
    if (sunIcon && moonIcon) {
      if (isDark) {
        sunIcon.style.display = 'block';
        moonIcon.style.display = 'none';
      } else {
        sunIcon.style.display = 'none';
        moonIcon.style.display = 'block';
      }
    }
  }

  // Update icon on initial load
  if (sunIcon && moonIcon) {
    updateThemeIcon();
  }

  if (!themeToggle) {
    return;
  }

  themeToggle.addEventListener('click', function(e) {
    e.preventDefault();

    // Get current theme from html element
    const htmlElement = document.documentElement;
    const isDark = htmlElement.classList.contains('theme-dark');
    const newTheme = isDark ? 'light' : 'dark';

    // Remove both theme classes
    htmlElement.classList.remove('theme-light', 'theme-dark');

    // Add the new theme class
    htmlElement.classList.add(`theme-${newTheme}`);

    // Persist to localStorage
    localStorage.setItem('theme', newTheme);

    // Update icon display
    updateThemeIcon();

    // Update Feather Icons if available
    if (window.feather) {
      window.feather.replace();
    }
  });
});