Home > OS >  Change CSS with JS for a toggled class
Change CSS with JS for a toggled class

Time:11-28

I'm learning JS right now, and I trying to do the following:

I'm creating an html grid, each cell is marked with a cell class which doesn't give it a background color. When I mark the cell (i.e by clicking), the JS code adds it a colored class, which gives it background color:

.colored{
    background-color: black;
}

Now, I'm trying to take it a step forward and give the user control over the background color of the cells by using HTML's input (type color). I'm getting the color the user picked, and then I want to change the cells background colors - and here is my problem.

I want to get the css rule for colored class and change it to the value supplied by the user. I tried changing it by using (colorPicker is the input element):

colorPicker.addEventListener('input', (e) => {
        cells.forEach((cell) => {
            if(cell.classList.contains('colored')) 
                cell.style.backgroundColor = e.target.value;
        })
    })

The above change only the cells which currently have colored class, and not the colored ruleset itself - so the cells which will be marked later won't get the color change.

I've come across ways to change the css ruleset directly by using document.styleSheets, but I'm looking for a more elegant way to change the colored class css.

Is there such a way?

CodePudding user response:

You could implement the same behavior with CSS variables. But instead of changing the style of a specific element you can change the value of the property.

A simple version can be used like so:

const colorPicker = document.querySelector('.color-picker');

colorPicker.addEventListener('input', (event) => {
  // Retrieve chosen color
  const color = event.target.value;
  
  // Overwrite CSS variable
  document.documentElement.style.setProperty('--color-red', color);
}, false);
:root {
  --color-red: #ff0000;
}

.colored {
  background-color: var(--color-red);
  margin: 0 0 0.25em;
}
<div class="colored">Am I red?</div>
<div class="colored">Should I be red?</div>
<div class="colored">Red is my color?</div>
<div class="colored">All I want is red?</div>
<div class="colored">Roses are red?</div>

<input type="color" class="color-picker" />
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related