Skip to content
Advertisement

Change CSS with JS for a toggled class

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:

JavaScript

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):

JavaScript

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?

Advertisement

Answer

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:

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement