Brandon Sherman
Brandon Sherman

Reputation: 674

How can I get a button in Shiny to call both JavaScript and R code in parallel?

I have an HTML button in Shiny that when clicked, calls the JavaScript function geocodeAddressStreet(...) in a .js file in the /www directory:

tags$body(tags$input(type = "button", 
                     value = "Next", 
                     id = "button1", 
                     onClick = "geocodeAddressStreet(houseNumber,streetName,addressCity,addressState)"))),

However I cannot figure out how to get this button to call a second file when clicked, let's say foo.R. Both procedures run independently, but it seems like there's no way to add an inputId to an HTML element in Shiny. We currently have two different buttons, one of which calls R code and the other of which calls JavaScript code, but this is clearly an impractical solution.

Upvotes: 8

Views: 4388

Answers (1)

DeanAttali
DeanAttali

Reputation: 26363

So you want to have a button and when you click it, both a javascript function and some R code get called? I was able to do this with the onclick function from the shinyjs package (disclaimer: I wrote the package)

library(shinyjs)

jsCode <- "
shinyjs.geocodeAddr = function(params) {
  alert('JavaScript called!');
  // geocodeAddressStreet(...)
}
"

runApp(shinyApp(
  ui = fluidPage(
    useShinyjs(),
    extendShinyjs(text = jsCode),
    actionButton("btn", "Click me")
  ),
  server = function(input, output, session) {
    onclick("btn", {
      js$geocodeAddr()
      cat("R called as well")
    })
  }
))

Basically, the onclick function is an R function that will run when the button is clicked. Within it you can obviously call R code easily, but you can also call JS code using the shinyjs package -- that's how I made a call to js$geocodeAddr. Look at the extendShinyjs function. Alternatively, instead of using extendShinyjs(), you can also use the usual approach of session$sendCustomMessage(...)

Upvotes: 7

Related Questions