Thursday, 4 November 2021

How to change all :root variables with one function

Similar question : But can't able to get answer

Can be answer to this question : But has to split on each :

If possible to get all variable in one function and change each values

If there are 2-4 variable than easy to change but when that change to 10 or more

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

function func() {
  root.style.setProperty('--r', 'brown');
  root.style.setProperty('--b', 'lightblue');
  root.style.setProperty('--g', 'lightgreen');
}
:root {
  --r: red;
  --b: blue;
  --g: green;
}

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

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

.text3 {
  color: var(--g)
}
<div class="text1">Hello</div>
<div class="text2">Bye</div>
<div class="text3">World</div>
<button onclick="func()">Change</button>

Is there a way to automatic(dynamically) get all the variables without writing each variable while values array is self entered

var root = document.querySelector(':root');
var roots = getComputedStyle(root);
var re = roots.getPropertyValue('--r')
var bl = roots.getPropertyValue('--b')
var gr = roots.getPropertyValue('--g')


function func() {
  root.style.setProperty('--r', 'brown');
  root.style.setProperty('--b', 'lightblue');
  root.style.setProperty('--g', 'lightgreen');
}

function func2() {
  root.style.setProperty('--r', re);
  root.style.setProperty('--b', bl);
  root.style.setProperty('--g', gr);
}
:root {
  --r: red;
  --b: blue;
  --g: green;
}

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

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

.text3 {
  color: var(--g)
}
<div class="text1">Hello</div>
<div class="text2">Bye</div>
<div class="text3">World</div>
<button onclick="func()">Change</button>
<button onclick="func2()">Orignal</button>

But when getting back to original values then each value is entered by separate variable and for each it is defined .
Is there a way to have a approach which takes original values and variables in separate array automatically.

Thanks for help in advance



from How to change all :root variables with one function

No comments:

Post a Comment