Tlatwork
Tlatwork

Reputation: 1525

Style element by index number in R Shiny

I want to color elements according to their index number in R Shiny (first match blue, second yellow, third red).

Reproducible example:

library(shiny)

ui <- fluidPage(
  tags$style(".control-label:nth-of-type(1) {background-color:blue;}"),
  tags$style(".control-label:nth-of-type(2) {background-color:yellow;}"),
  tags$style(".control-label:nth-of-type(3) {background-color:red;}"),

  lapply(
    letters[1:3], 
    FUN = function(name){
      selectizeInput(
        inputId = paste0("type_", name),
        label = paste0(name),
        choices = "a",
        selected = "a",
        multiple = TRUE,
        options = list(create = TRUE)
      )
    }
  )

)

server <- function(input, output, session) {

}

shinyApp(ui, server)

What i tried:

According to: CSS selector for first element with class i see a few Options:

Upvotes: 0

Views: 50

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84529

I don't know a CSS solution. Here is a JavaScript solution:

library(shiny)

js <- '
$(document).ready(function(){
  var labels = $(".control-label");
  labels[0].style.backgroundColor = "red";
  labels[1].style.backgroundColor = "green";
  labels[2].style.backgroundColor = "blue";
});
'

ui <- fluidPage(
  tags$head(tags$script(HTML(js))),
  lapply(
    letters[1:3], 
    FUN = function(name){
      selectizeInput(
        inputId = paste0("type_", name),
        label = paste0(name),
        choices = "a",
        selected = "a",
        multiple = TRUE,
        options = list(create = TRUE)
      )
    }
  )

)

server <- function(input, output, session) {}

shinyApp(ui, server)

Upvotes: 1

Related Questions