Picture-element : state label with conditional color

Hi all,
I need some help with making a sensor state-label color depend on the state of a switch.
I tried several possibilities like the one below

cards:
  - type: picture-elements
    image: /local/images/Energy3.png
    elements:
     - name: Kitchen Coffee Power Real Time
        type: state-label
        entity: sensor.kitchen_coffee_power
        style:
          top: 55.4%
          left: 42.5%
          color: >
                [[[
                  if (states['switch.kitchen_coffee'].state === 'on' )
                    return "yellow";
                  if (states['switch.kitchen_coffee'].state === 'off' )
                    return "green";
                  else return "steelblue";
                ]]]

but nothing happens. Text stays white.
What am I doing wrong?
PPee

I’ve not seen JavaScript used in the picture elements card in this way. Are you sure this is supported?

The only time I’ve seen something like this is in the HACS custom button card.

You can use the custom button card in the picture elements card using the hui-element HACS integration.

I may be wrong.

Yeah it is not supported. I use card mod to do this sort of thing:

elements:
  - type: state-label
    entity: sensor.tank_temperature
    style:
      top: 48%
      left: 40.5%
    card_mod:
      style: |
        :host {
          color:
              {% set temp = states('sensor.tank_temperature')|float(0) %}
              {% if temp > 50 %}
                #e45e65
              {% elif temp > 40 %}
                #e0b400
              {% elif temp > 30 %}
                #0da035
              {% else %}
                #039BE5
              {% endif %}
4 Likes

@tom_l Thanks for this example. I created a flood warning map using the Environment Agency integration and while I could get the levels to show on a map, changing the colour of the value based on the flood level would have been even better. I tweaked your example and managed to get it to work in my example.

Not being knowledgeable of this sort of thing, I’m not sure what the float(0) element does but I left it as the same and it seems to work a treat.

State values are strings. Before you can do mathematical operations like greater than or less than you need to convert them to numbers.

|float converts to a floating point number
|int converts to an integer

The numbers in brackets after it are the default value that will be used if the state value can not be converted to a number. See: Templating - Home Assistant

1 Like

Thanks for the explanation @tom_l that helps. It’s a good job I left it in then otherwise I suspect it would not have worked!

1 Like

Thanks, I’ve been looking for this for a while!