Search code examples
rshinyshinyjs

How to hide/show several elements at once with shinyjs?


How to hide/show several elements at once with shinyjs? In the following example my goal is to hide/show both tables with just two lines of code instead of four. Why do I want to do this? In reality, I am dealing with several tables and several events such that showing/hiding them all at once would keep the code a lot cleaner.

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  actionButton("hide","Hide!"),
  actionButton("show","Show!"),
  tableOutput("table1"),
  tableOutput("table2"))

server <- function(input, output, session) {
  output$table1 <- renderTable({head(iris)})
  output$table2 <- renderTable({head(iris)})
  observeEvent(input$hide, {hide("table1")})
  observeEvent(input$show, {show("table1")})
  observeEvent(input$hide, {hide("table2")})
  observeEvent(input$show, {show("table2")})}

shinyApp(ui, server)

Solution

  • You can write a function that performs both operations and call them once per ui element that you want to hide/show.

    library(shiny)
    library(shinyjs)
    
    toggleView <- function(input, output_name){
      observeEvent(input$show, {show(output_name)})
      observeEvent(input$hide, {hide(output_name)})
    }
    
    ui <- fluidPage(
      useShinyjs(),
      actionButton("hide","Hide!"),
      actionButton("show","Show!"),
      tableOutput("table1"),
      tableOutput("table2"))
    
    server <- function(input, output, session) {
      output$table1 <- renderTable({head(iris)})
      output$table2 <- renderTable({head(iris)})
      toggleView(input, "table1")
      toggleView(input, "table2")
    }
    
    shinyApp(ui, server)
    

    You can also go one step further and vercorize this function with respect to output_name. Make sure to use lapply rather than for however, since the latter can run into problems with lazy evaluation.

    toggleViews <- function(input, output_names){
      lapply(output_names, function(output_name){
        toggleView(input, output_name)
      })
    }
    
    ...
    
    toggleViews(input, c("table1", "table2"))