Change css class on entity value change

I want to set different css classes based on the current entity value.
Tried this but it’s not working.

- entity: sensor.heatpump_icon_fanspeed
              element: heatpump.fan
              state_action:
                service: floorplan.class_set
                service_data: |-
                  {
                    if (entity.state === "1"){
                      return "spinning";
                    } else {
                      return "spinninghigh";
                    }
                  }
              tap_action: false

Check to see if there are any non-numeric characters in the state. I also always parse them to a value and then do the check. So something like:

        - entity: sensor.heatpump_icon_fanspeed
          element: heatpump.fan
          state_action:
            service: floorplan.class_set
            service_data: |
              >
                if (parseInt(entity.state) == 1) return "spinning";
                else return "spinninghigh";
          tap_action: false
1 Like

Thank you,

Works almost perfectly.
Can I also make more cases?

           service_data: |
              >
                if (parseInt(entity.state) == 1) return "spinning";
                elseif (parseInt(entity.state) == 2) return "spinninghigh";

Yes you can do it that way. You can also assign the state value to a variable and then check that.

speed = parseInt(entity.state)

It’s all just JavaScript

Perhaps I’m missing something.

service_data: |
     >
        if (parseInt(entity.state) == 1) {
            return 'spinning';
        } else if (parseInt(entity.state) == 2) {
            return 'spinningmid';
        } else if (parseInt(entity.state) == 3) {
            return 'spinninghigh';

I don’t see what i’m doing wrong.

You didn’t mention what is going wrong but I can suggest that you don’t need the final IF. Just have

Else return “spinning high”;

Edit: check your indenting as well

I want to set a (different) class, when the heatpump is working. I can of ofcourse make a class for not spinning.
Made a screenshot of the code, because the editor doen’t show the indenting correct.
image

If I try your example it works perfectly, but mine doesn’t
everything below the javascript don’t get executed.
I can not figure out why.

I’m assuming the entity has the state of 1, 2 or 3 only.

Try double quotes around the return value