Search code examples
javascriptcsssasscss-variables

Why can't update css variable name to apply a different color theme?


I want to switch between two css themes in an else/if statement built in scss by changing a single custom variable via javascript.

I see lots of examples out there about how change one or two colors in css variables via javascript, but I want to change the whole theme of a site by changing a $theme variable only.

Check the codepen: https://codepen.io/roroland/pen/gVWLBm

// Var defaults
$theme: default;
$primary: null;
$warn: null;
:root {
  --theme: #{$theme};
}

// If theme is 'default' use this
@if ( $theme == "default") {
  $primary: orange;
  $warn: purple;
}
// If theme is 'other' use this instead
@elseif($theme == "other") {
  $primary: black;
  $warn: blue;
}

p {
  display: block;
  padding: 2rem;
  color: $primary;
  background: $warn;
}

JS

document.documentElement.style.setProperty('--theme', "other");

If I try to update $theme it doesn't work, I tried with and without interpolation, setting 'null' the theme var, etc.. it just ignore the JS instruction.

Can someone explain why isn't working? Thanks


Solution

  • This is a job for CSSVariables (dynamic) that unlike Sass variables (static) works at run-time.

    /* toggle theme class */
    addEventListener('click', e => {
      document.documentElement.classList.contains('other') ?
        document.documentElement.classList.remove('other') :
        document.documentElement.classList.add('other');
    })
    /* default theme */
    :root {
      --primary: orange;
      --warn: purple;
    }
    
    /* other theme */
    :root.other {
      --primary: black;
      --warn: blue;
    }
    
    p {
      display: block;
      padding: 2rem;
      /* use theme colors */
      color: var(--primary);
      background: var(--warn);
    }
    <h2>Click to toggle theme class</h2>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Distinctio dolorem quas quod eaque voluptatem error, rem vero non. Eveniet maxime saepe fugiat tenetur dignissimos enim, provident earum illo quasi fugit?</p>