How to Change CSS :Root Color Variables in JavaScript

How to change CSS :root color variables in JavaScript

Thank you @pvg for providing the link. I had to stare at it for a little to understand what was going on, but I finally figured it out.

The magical line I was looking for was this:

document.documentElement.style.setProperty('--your-variable', '#YOURCOLOR');

That did exactly what I wanted it to do, thank you very much!

Updating a root css style through JavaScript

You can do something like,

document.documentElement.style.setProperty('--property', 'color');

You can visit this link for a demo created by wesbos.

Change CSS root variable with jquery or javascript

You can do this pretty easy with something like:

document.documentElement.style.setProperty('--themeColor', 'red');

Update:
Not sure if the question was just about changing the color as I thought. Now I've also added a getRandomColor() example. Just to get random stuff can be a big load of work depending if you want to save the last used color by the user or so ...

// array with colorsvar colors = [  "red",  "green",  "lime",  "purple",  "blue"];
// get random color from arrayfunction getColor() { return colors[ Math.floor(Math.random() * colors.length) ];}
// Set the color from arraydocument.documentElement.style.setProperty('--themeColor', getColor());
:root {    --themeColor: orange;}
a { color: var(--themeColor)} div { width: 100px; height: 100px; background-color: var(--themeColor);}
<a href="#">Hello world</a><div>Test</div>

How can I change CSS variable on button click?

You are trying to change the value of one variable with another variable.

You will need getComputedStlye():

:root{
--in: inset 25px 25px 60px red;
--out: inset -25px -25px 60px green;
}
.color_1{
background-color: blue;
border-radius: 200px;
height: 300px;
width: 300px;
box-shadow: var(--out);
}
<body>
<section>
<button class="color_1">

</button>

<script>
const btn = document.querySelector('button')
const state = '--out'
btn.addEventListener('click', _ =>{ document.documentElement.style.setProperty(state, getComputedStyle(document.documentElement).getPropertyValue('--in'));
});
</script>

</section>
</body>

How to change all :root variables with one function

I understand you want to first read all the declared variables from the css and store them, so they might be resetted after applying new values?
This code will do this, given that there's just one ':root' declaration in one stylesheet (easily complemented in case 'splitted' declaration in more places needed)

let variableLookup = {
'--r': {
newValue: 'teal'
},
'--b': {
newValue: 'orange'
},
'--g': {
newValue: 'purple'
}
}

var root = document.querySelector(':root');

function setNewColors() {

const cssText = [...document.styleSheets]
.map(styleSheet => [...styleSheet.cssRules]
.filter(CSSStyleRule => CSSStyleRule.selectorText === ':root'))
.flat()[0].cssText

// cssText = ':root { --r: red; --b: blue; --g: green; }'

cssText.match(/{(.*)}/)[1].trim()
.split(';')
.filter(Boolean)
.forEach(declaration => {
const [variable, oldValue] = declaration.split(':').map(str => str.trim())
let entry = variableLookup[variable]
if (entry) entry.oldValue = oldValue
})

console.log('variableLookup >>', variableLookup)

Object.entries(variableLookup).forEach(([variable, {newValue}]) => {
root.style.setProperty(variable, newValue);
})
}

function resetColors() {
Object.entries(variableLookup).forEach(([variable, {oldValue}]) => {
if (oldValue) root.style.setProperty(variable, oldValue)
})
}
:root {
--r: red;
--b: blue;
--g: green;
}

.text1 {
color: var(--r)
}

.text2 {
color: var(--b)
}

.text3 {
color: var(--g)
}

:root {
--c: magenta;
}
<div class="text1">Hello</div>
<div class="text2">Bye</div>
<div class="text3">World</div>
<button onclick="setNewColors()">Change to new colors</button>
<button onclick="resetColors()">Reset old colors</button>

How to setup a simple color scheme via CSS Root Variables?

There are three problems to address in your JavaScript code:

  1. The value property on an element does not refer to the attribute that you have named value on your paragraph elements. To access the value of this property, you'll need to use Element.getAttribute().

  2. this in your event listener callback function does not refer to the target element of the event. To access the target element, you'll need to use Event.target.

  3. The event that you want to listen for is most likely the click event (not the change event).

const setTheme = theme => document.documentElement.className = theme;
document.getElementById('themeoptions').addEventListener('click', ({target}) => {
setTheme(target.getAttribute('value'));
});
#themeoptions p{ /* User Interface */
display: inline-block;
text-decoration: underline;
}#themeoptions p:hover{cursor: pointer}

:root.light {
--bgr: #ddc;
--txt: #456;
}
:root.dark {
--bgr: #222;
--txt: #844;
}
:root.blue {
--bgr: #046;
--txt: #dde;
}

body {
background-color: var(--bgr);
color: var(--txt);
}
<div id="themeoptions">
<p value="light">Light</p>
<p value="dark">Dark</p>
<p value="blue">Blue</p>
</div>

<h1>Click on a theme to change the color scheme!</h1>

How to change CSS root variable in React?

Finally found solution

constructor(props){
super(props);
this.state = {color: '#3C454B'};
}
changeTheme(e){
this.setState({color: event.target.value});
document.documentElement.style.setProperty('--base',this.state.color);
}

class App extends React.Component {
render() {
return (
<div className="row">
<div className="col-xs-12 text-center">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Aliquam voluptates ut eaque, voluptatum veniam nostrum sequi numquam sint, excepturi amet unde quis, ipsum ducimus reprehenderit eligendi pariatur animi esse sed.</p>
<input
className=""
type="color"
defaultValue={this.state.color}
onChange={(e) => this.handleColor(e)}
/>
<br/><br/>
</div>
</div>
);
}
}

ReactDOM.render(<App />, window.document.getElementById('myDiv'));

How to use css variable colors and js to change div background

You can add a data-color attribute to your buttons which specifies the color (variable) to change to when clicking on the given button. Then you can add the click event listener to all your buttons with the class color-btn. Then when you click on a given button the event listener will be called, which will get the data attribute from the button clicked, and then use your changeColor function to change the div to the appropriate color (using the variable).

Also, you haven't defined your variables correctly. Firstly, you need to target the root using :root. Then you nee to set your variables using --variableName: COLOR. Lastly, in your changeColor function you need to use .style.backgroundColor = "var(--" +color +")" to correctly use the variable.

See working example below

[...document.getElementsByClassName("color-btn")].forEach(elem => {  elem.addEventListener('click', function() {    const btnColor = this.getAttribute('data-color');    changeColor(btnColor);  });})
function changeColor(color) { var element = document.getElementById('box'); element.style.backgroundColor = "var(--" +color +")";}
:root {  --w: #fff;  --b: #000;}
.box { width: 100px; height: 100px; border: 1px solid #aaa; background-color: #fff;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="box" id="box"></div>
<button class="color-btn" data-color='w'>white</button><button class="color-btn" data-color='b'>black</button>


Related Topics



Leave a reply



Submit