'SCSS data-theme="dark" variables doesnt load

im currently working on a dark mode for my site and the JS is working fine, it adds the data-theme="dark" parameter to the html tag and stores it in the local storage. But the variables in SCSS just wont load. Here is my code:

$colorMain: #9C27B0;
$colorDisabled: rgb(92, 92, 92);

$colorTextWhite: #FFF;
$colorTextBlack: #000;
$colorTextTitle: #2b2b2b;
$colorTextPara: #4e4e4e;

$colorBgMain: #FFF;
$colorBgSec: darken($colorBgMain, 3%);

$colorAlertSuccess: #8BC34A;
$colorAlertDanger: #F44336;

$colorDarkMode: #272727;

[data-theme="dark"] {
    $colorMain: rgb(176, 39, 39);
    $colorDisabled: rgb(92, 92, 92);

    $colorTextWhite: #FFF;
    $colorTextBlack: #000;
    $colorTextTitle: #2b2b2b;
    $colorTextPara: #4e4e4e;

    $colorBgMain: rgb(0, 0, 0);
    $colorBgSec: darken($colorBgMain, 3%);

    $colorAlertSuccess: #8BC34A;
    $colorAlertDanger: #F44336;

    $colorDarkMode: #ffffff;
}

JS:

const toggleSwitch = document.querySelector('input[name="mode"]');

function switchTheme(e) {
    if (e.target.checked) {
        trans()
        document.documentElement.setAttribute('data-theme', 'dark');
        localStorage.setItem('theme', 'dark'); //add this
    } else {
        trans()
        document.documentElement.setAttribute('data-theme', 'light');
        localStorage.setItem('theme', 'light'); //add this
    }    
}

toggleSwitch.addEventListener('change', switchTheme, false);

const currentTheme = localStorage.getItem('theme') ? localStorage.getItem('theme') : null;

if (currentTheme) {
    document.documentElement.setAttribute('data-theme', currentTheme);

    if (currentTheme === 'dark') {
        toggleSwitch.checked = true;
    }
}

let trans = () => {
    document.documentElement.classList.add('transition');
    window.setTimeout(() => {
        document.documentElement.classList.remove('transition');
    }, 1000)
}

Can somebody help me? :D



Solution 1:[1]

The variables can't just load, you have to use some preprocessing lib to convert them. Alternatively I'd recommend you to use css variables if it fits your use case.

Look second implementation of this article. I've tested the code, it should work for you. Cheers :)

Solution 2:[2]

First, define your variables based on the data themes:

:root[data-theme="light"] {
  --general-bg-color: #fff
}
:root[data-theme="dark"] {
  --general-bg-color: #333
}

Then, use the colors independently of the data theme:

.someClass {
   background-color: var(--general-bg-color)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shravan Dhar
Solution 2 hunter