0

I wanted to change colors of my <h1>, <h2> and <h3> tags.

I've declared several variables in css like this:

:root{
    --color1 : #E11F28;
    --color2 : #F8981D;
    --color3 : #1DAD4B;
}

My question is how can I get that value and change it automatically with javascript in several times and loop (from number 1 into 3)

Leone
  • 3,258
  • 3
  • 22
  • 28

2 Answers2

0

Here's a simple example

of course, you'll need to figure out how to get the right rule to change by changing

var declaration = document.getElementById('x').sheet.rules[0].style;

Seeing as you've written no javascript yourself, and shown absolutely nothing except a single style rule, that's one thing at least you'll need to figure out for yourself

but ... it works

function changecolors() {
  const changeit = style => {
    let p = style.getPropertyValue('color').replace(/\d/, x => x%3 + 1);
    style.setProperty('color', p);
  }
  var declaration = document.getElementById('x').sheet.rules;
  changeit(declaration[0].style)
  changeit(declaration[1].style)
  changeit(declaration[2].style)
}
setInterval(changecolors, 1000);
:root {
  --color1: #E11F28;
  --color2: #F8981D;
  --color3: #1DAD4B;
}
<style id="x">
  h1 {
    color: var(--color1);
  }
  
  h2 {
    color: var(--color1);
  }
  
  h3 {
    color: var(--color1);
  }
</style>


<h1>H1</h1>
<h2>H2</h2>
<h3>H3</h3>
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
0

what i really wanted is like this

let html = document.querySelector(`html`);

var color = ['red', 'green', 'blue'];
var i =0;

let uid = setInterval(() => {
    i = (i+1)%color.length;
    change = color[i];
    html.style.setProperty(`--theme`, `${change}`);
}, 1000);
:root {
  --theme : black;
}

h1 {
  color : var(--theme);
}
<h1>
  Text Goes Here
</h1>

big thx to my friend Muhammad vickry Yanto for creating this script

and thx for answering my question