Design comparison
Solution retrospective
I need to change the sass variables from Javascript
Community feedback
- Account deleted
Hi.
Since SASS is a CSS preprocessor all its information disappears when the code is compiled to CSS so it is not possible to change a SASS variable directly; however, if you're generating CSS variables from SASS you can change their values with Javascript.
let's suppose your variable is in the
root
element:: root { --bg-color: red; }
Then you set the background color with the variable's value:
body { background-color: var(--bg-color); }
You can change its value with
document.body.style.setProperty('--bg-color', 'blue');
The above could work but there's actually a better and more scalable approach and it's defining a group of variables called map
$themes: ( light: ( "text": black, "background": white, ), dark: ( "text": white, "background": black, ), );
As you can see, we have a map called themes and that object has two children (which in turn are map data as well), one for a light theme and another for dark theme and then you set a class to the body element and inside of that class, use the
@each
rule in order to get each value of the theme child property:body.light { @each $key, $value in map-get($themes, light) { --#{$key}: #{$value}; } background-color: var(--background); color: var(--text); } body.dark { @each $key, $value in map-get($themes, dark) { --#{$key}: #{$value}; } background-color: var(--background); color: var(--text); }
With that, you only need to change the class of the
body
element in order to switch between themes// Change from light to dark document.body.className = document.body.className.replace('light', 'dark'); // Change from dark to light document.body.className = document.body.className.replace('dark', 'light');
1@EnyelberPosted over 4 years ago@juanmesa2097 Thanks by the answer, is what I had in mind.
1Account deleted@Enyelber of course, no problem 👍
0
Please log in to post a comment
Log in with GitHubJoin our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord