Skip to contents

Switch between different icons or titles on a button.

Usage

toggle_icon(input_id, icons, one_way = FALSE)

toggle_title(input_id, titles, one_way = FALSE)

Arguments

input_id

character(1) (namespaced) id of the button

icons, titles

character(2) vector specifying values between which to toggle

one_way

logical(1) flag specifying whether to keep toggling; if TRUE, the target will be changed from the first element of icons/titles to the second

Value

Invisible NULL.

Details

Wrapper functions that use shinyjs::runjs to change button properties in response to events, typically clicking those very buttons. shiny's actionButton and actionLink create <a> tags, which may contain a child <i> tag that specifies an icon to be displayed. toggle_icon calls the toggleClass (when one_way = FALSE) or removeClass and addClass methods (when one_way = TRUE) to change icons. toggle_title calls the attr method to modify the Title attribute of the button.

Examples

if (FALSE) {

# continuously switch between right- and down-pointing chevrons
toggle_icon("toggle_element", c("fa-angle-right", "fa-angle-down"))

# switch right- to down-pointing chevron
toggle_icon("toggle_element", c("fa-angle-right", "fa-angle-down"), one_way = TRUE)
}

library(shiny)

ui <- fluidPage(
  shinyjs::useShinyjs(),
  actionButton("hide_content", label = "hide", icon = icon("xmark")),
  actionButton("show_content", label = "show", icon = icon("check")),
  actionButton("toggle_content", label = "toggle", icon = icon("angle-down")),
  br(),
  div(
    id = "content",
    verbatimTextOutput("printout")
  )
)

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

  observeEvent(input$hide_content, {
    shinyjs::hide("content")
    toggle_icon("toggle_content", c("fa-angle-down", "fa-angle-right"), one_way = TRUE)
  }, ignoreInit = TRUE)

  observeEvent(input$show_content, {
    shinyjs::show("content")
    toggle_icon("toggle_content", c("fa-angle-right", "fa-angle-down"), one_way = TRUE)
  }, ignoreInit = TRUE)

  observeEvent(input$toggle_content, {
    shinyjs::toggle("content")
    toggle_icon("toggle_content", c("fa-angle-right", "fa-angle-down"))
  }, ignoreInit = TRUE)

  output$printout <- renderPrint({
    head(faithful, 10)
  })

}

if (interactive()) {
  shinyApp(ui, server)
}