Changing a switch's colors according to its own value

#1

I want to change a toggle’s background and front colors according to its own value (that is, the selected button).

I have tried this code but it doesn’t function:
.value.on {
margin:0;
border:0;
#{
my_bcolors = [“blue”, “violet”, “violet” , “violet”, “violet”, “green”, “green”, “green”, “green”, “yellow”];
my_fcolors = [“white”, “white”,“white”,“white”,“white”,“white”,“white”,“white”,“white”, “black”];
couleur = @{this.value};
color:my_fcolors(couleur);
background:my_bcolors(couleur);
}
}

What’s wrong with my code?

#2

There are many issues here:

  • you are using invalid double quotes characters (maybe referred to as “smart quotes”, never ever use these in programmation languages, stick to the basic ")
  • your formula (the #{} block) doesn’t output anything because all lines end with semi-colons
  • my_fcolors(couleur) is not valid, you should write my_fcolors[couleur] using brackets instead of parenthesis
  • these statements are invalid:
color:my_fcolors(couleur);
background:my_bcolors(couleur);

You are mixing css and mathjs syntaxes here, mathjs syntax must be stricltly respected inside #{} blocks.

When your code is getting complicated, it can help to separate the calculation from the rendering:

#{
  my_bcolors = ["blue", "violet", "violet" , "violet", "violet", "green", "green", "green", "green", "yellow"];
  my_fcolors = ["white", "white","white","white","white","white","white","white","white", "black"];
  couleur = @{this.value};
  color = my_fcolors[couleur];
  bcolor = my_bcolors[couleur];
  # variables are computed but not printed
}
.value.on {
  margin:0;
  border:0;
  /* now we use them */
  color: #{color};
  background: #{bcolor};
}
#3

Thanks a lot, it makes all this stuff much more clear to me!