Switch widget, iterate single switches

Hi all,

first of all, thanks a lot for this great Lemur alternative! :grinning: I’m currently trying to migrate my big Lemur projects over to O-S-C.
Coming from a ‘classical’ (read not object oriented) background, I’m struggeling with the different javascript possibilities.
Currently I’m trying to set the color of the buttons in a switch widget to different colors. The only solution I came up with, was to use css nth-child and attach a variable via @{color_var} to every nth-child. Actually I would prever a solution where I can iterate over an array containing the color values and assign them to the switches directly. Is there an iterator for the switches, similar to the ‘$’ used in the matrix? Thanks for your help

Is there an iterator for the switches, similar to the ‘$’ used in the matrix? Thanks for your help

No, but you could use a for loop to the same effect:

JS{{
var colors = ["red", "blue", "cyan", "lime"]
var css = ''
for (var i = 0; i < colors.length; i++) {
  css += "value:nth-child(" + (i+1) + "){--color-fill:" + colors[i] + ";}\n"
}
return css
}}

Cool, thanks a lot. :grinning: I was not aware of the fact, that the returned string ‘css’ is simply inserted in the whole css block. Its actually pretty simple… I always thought you have to pass the result to a property or similar.
I also read about backticks (gravis?), which could be used to concat strings, I thought about using these. But I prefer your solution, since it looks familiar to me.

Using backticks (aka template literals) it would like this:

  css += `value:nth-child(${i + 1}){--color-fill:${colors[i]};}\n`

Note: $ here has nothing to do with the variable used as index in the matrix’ props property

me neither ! a very good tip ! @jean-emmanuel has some secrets :slight_smile:

It’s the default behavior for all the advanced syntax blocks: they end up replaced with the returned value and then the property is evaluated by the widget.

ok so the variable name css returned can be truc

JS{{
var colors = ["red", "blue", "cyan", "lime"]
var truc = ''
for (var i = 0; i < colors.length; i++) {
  truc += "value:nth-child(" + (i+1) + "){--color-fill:" + colors[i] + ";}\n"
}
return truc
}}

Absolutely