Jquery inside observeEvents

Viewed 43

I am trying to use Jquery inside observeevent but not able to execute it. The moment I click on "Release" button , the side bar should open. I have a Jquery here but not working. But when I put the same jquery inside onclick method, it works. But not in this method

library(shiny)
library(shinydashboard)
library(shinyjs)

ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(collapsed = TRUE),
  dashboardBody(
    # Boxes need to be put in a row (or column)
actionButton("release", "Release"))
    )


server <- function(input, output) {

  useShinyjs()
  observeEvent(input$release,{
    tags$head(tags$script("$('body').toggleClass('sidebar-collapse');"))
  })
}

shinyApp(ui, server)
1 Answers

Using Shiny

Shiny ships with some jQuery/Bootstrap functions built in for convenience, toggleClass being one of them. To use it, move useShinyjs() somewhere into or after the dashboardBody (don't forget the comma), and replace your jQuery code with a call to toggleClass:

library(shiny)
library(shinydashboard)
library(shinyjs)

ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(collapsed = TRUE),
  dashboardBody(
    useShinyjs(),                                               ## <<<
    actionButton("release", "Release")
  )
)

server <- function(input, output) {
  observeEvent(input$release, {
    toggleClass(selector = "body", class = "sidebar-collapse")  ## <<<
  })
}

shinyApp(ui, server)

Using jQuery

You can also extend the available functions by adding custom ones (including jQuery calls just like yours) using extendShinyjs, and then invoke them using js. Prepend their name (e.g. toggleCollapse) with the shinyjs. prefix in the definition, and register them for later use with js in the functions argument.

library(shiny)
library(shinydashboard)
library(shinyjs)

ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(collapsed = TRUE),
  dashboardBody(
    useShinyjs(),                                               ## <<<
    actionButton("release", "Release"),
    extendShinyjs(                                              ## <<<
      text = "shinyjs.toggleCollapse = function() {             // <<<
        $('body').toggleClass('sidebar-collapse');              // <<<
      }",                                                       ## <<<
      functions = c("toggleCollapse")                           ## <<<
    ),                                                          ## <<<
  )
)

server <- function(input, output) {
  observeEvent(input$release, {
    js$toggleCollapse()                                         ## <<<
  })
}

shinyApp(ui, server)
Related