Cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

How to update a CSS class via JavaScript question

I have the following style in my styles.css:

.foreground-fill { fill: fb-white; }

 

Is there a way to update the color of this style using javascript?

I tried this, but it didn't work:

let forgroundFill = document.getElementById("forground-fill");

let color = JSON.parse(evt.data.newValue);
forgroundFill.style.fill = color; (foregroundFill seems to be null)

Best Answer
0 Votes
2 REPLIES 2

You can't redefine classes using JS in the Fitbit system.

 

However, you can change which class(es) apply to an element, so you may be able to achieve what you want using multiple classes.

Peter McLennan
Gondwana Software
Best Answer
0 Votes

I think the real issue is that "document.getElementById" is being used improperly. It is not used to retrieve references to CSS class names (as your code seems to show). Instead, it is used to get references to SVG tag objects, for which the class name and style properties are accessible. The SVG tag must have a unique ID property.

 

For example, if my SVG contains something like:

 

<image id="iconSteps" fill="fb-white" href="stat_steps_open_48px.png" />

 

JavaScript would reference that object like this:

 

let iconStepsReference = document.getElementById("iconSteps");

 

And you can replace the style "fill" property with this:

 

iconStepsReference.style.fill = "fb-violet";

 

You are getting a null reference because there is probably no SVG element with an ID of "foreground-fill". Since you are using a class name in your SVG markup, you might consider replacing the entire class name, as Gondwana replied.

 

So, if your CSS has:

 

.foreground-fill { fill: fb-white; }
.new-foreground-fill { fill: fb-violet; }

 

And your SVC contained something like this:

 

<image id="iconSteps" class="foreground-fill" href="stat_steps_open_48px.png" />

 

Your JavaScript would look like this:

 

let iconStepsReference = document.getElementById("iconSteps");
iconStepsReference.className = "new-foreground-fill";

 

Notice that the SVG tag property is "class" but the JavaScript property is "className".

 

Alternatively, the Fitbit JavaScript does support "document.getElementsByClassName" if you were trying to select multiple SVG tags with the same CSS class name. But then, you'd have to loop through each element and replace the class name.  Either way, the issue is that you can't use "document.getElementById" that way.

Best Answer
0 Votes