Steve Powell
Steve Powell

Reputation: 1698

how to get the id of a span in dynamic output in shiny

I can get the id of a span element in Shiny using js thanks to Stephane but not if the element is produced dynamically (indeed the contents of the dynamic elements are not contained in the source code of the HTML page produced). Any ideas how I can access the ids also of dynamic elements?

library(shiny)

js <- "
$(document).ready(function(){
  $('span').on('mouseover', function(evt){
    Shiny.setInputValue('span', evt.target.id);
  });
})
"

ui <- basicPage(
  tags$head(tags$script(HTML(js))),
  tags$div(
    tags$span(id = "span1", "foo"),
    tags$span(id = "span2", "bar")
  ),                                   # mousing over these spans triggers the output in the verbatimTextOutput
  br(),
  uiOutput("dynamicArea"),             # mousing over these spans does NOT trigger the output in the verbatimTextOutput
  br(),
  verbatimTextOutput("span")
)

server <- function(input, output){
  output[["span"]] <- renderPrint({
    input[["span"]]
  })

output[["dynamicArea"]] <- renderUI({
  tags$div(
    tags$span(id = "spandynamic1", "foo2"),
    tags$span(id = "spandynamic2", "bar2") 
  ) 
})
}
shinyApp(ui, server)

Upvotes: 1

Views: 722

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84649

Use this JS code:

js <- "
$(document).ready(function(){
  $('body').on('mouseover', 'span', function(evt){
    Shiny.setInputValue('span', evt.target.id);
  });
})
"

Upvotes: 1

Related Questions