Search code examples
javascripthtmlcss

Use css var for changing dynamically the style


I try to use css var for changing dynamically an html page .

Here I have an exemple where I try to implement a dark mode switch.

 const toggleDarkModeBtn = document.getElementById('toggle-dark-mode');

        toggleDarkModeBtn.addEventListener('click', () => {
            document.body.classList.toggle('dark');
            
            if (document.body.classList.contains('dark')) {
                toggleDarkModeBtn.textContent = 'Disable Dark Mode';
            } else {
                toggleDarkModeBtn.textContent = 'Enable Dark Mode';
            }
        });
:root {
    --bg-color: #862e2e;
    --text-color: #ffffff;
}

.dark :root {
  --bg-color: #2d3748;
  --text-color: #e2e8f0;
}

body {
  background-color: var(--bg-color);
  color: var(--text-color);
}
<header>
        <h1>Dark Mode Attempt</h1>
        <button id="toggle-dark-mode">Enable Dark Mode</button>
    </header>
    <main>
        <p>Click the button to toggle between modes.</p>
    </main>

It add and remove the class dark on the root element but the page is not toggling the style.

Do you know what is the issue and how to use css var for changing style dynamically?


Solution

  • The :root refers to the <html> element (the root element). So toggle the class dark on that element (not on the <body>). You can get it with const rootElement = document.documentElement

    Also note the selector for the dark theme should be :root.dark

    const toggleDarkModeBtn = document.getElementById('toggle-dark-mode');
    const rootElement = document.documentElement;
    
    
    toggleDarkModeBtn.addEventListener('click', () => {
      rootElement.classList.toggle('dark');
    
      if (rootElement.classList.contains('dark')) {
        toggleDarkModeBtn.textContent = 'Disable Dark Mode';
      } else {
        toggleDarkModeBtn.textContent = 'Enable Dark Mode';
      }
    });
    :root {
      --bg-color: #862e2e;
      --text-color: #ffffff;
    }
    
    :root.dark {
      --bg-color: #2d3748;
      --text-color: #e2e8f0;
    }
    
    body {
      background-color: var(--bg-color);
      color: var(--text-color);
    }
    <header>
      <h1>Dark Mode Attempt</h1>
      <button id="toggle-dark-mode">Enable Dark Mode</button>
    </header>
    <main>
      <p>Click the button to toggle between modes.</p>
    </main>