James
James

Reputation: 235

How can I dynamically change the background colour for a wellPanel in a shiny app/module?

I have a shiny module that organizes user input elements in a number of wellPanels.

I would like these panels to change their background based on whether the user has filled in the elements appropriately; i.e. start out with a red background when empty, then change to a green background after they've filled in a couple text inputs.

My code is already able to validate the user's input, I just don't know how to change the background colour of the wellPanels.

My code is setup like this:

myModuleInput <- function(id) {
  ns <- NS(id)

  tagList(
    wellPanel(
      # Some inputs
    ),
    wellPanel(
      # Some more inputs
    )
  )
}

Upvotes: 1

Views: 1293

Answers (1)

Grant
Grant

Reputation: 356

You can use the shinyjs library to run javascript that changes the color of the wells, provided you give them an id.

The js code is element.style.backgroundcolor = color. Shinyjs provides runjs() to use that. Don't forget to call useShinyjs() in your ui.

Full code:

# LIBRARIES & SOURCING --------------
library(shiny)
library(shinydashboard)
library(shinyjs)

# UI -----------------
ui <- dashboardPage(title="App Title", 
                    dashboardHeader(disable = TRUE),
                    dashboardSidebar(disable = TRUE),
                    dashboardBody( 
                        useShinyjs(),
                        fluidRow(
                            wellPanel(
                                tags$p("Some text"), 
                                id = "wellPanelId1"
                            )
                        )
))



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

    observe({
        # some event
        runjs(sprintf("
            document.getElementById('%s').style.backgroundColor = '%s';
        ", "wellPanelId1", "#00FF00"))
    })

}

shinyApp(ui = ui, server = server)

Upvotes: 2

Related Questions