Access jQuery user interface elements created on the back of the Shiny application

I want to pass the Shiny ID of an element of a specific pseudo-class when I click it. Everything works fine if the user interface elements are created in the user interface of the Shiny application. But when the user interface is created on the server side (via renderUI), it does not work. The following is a reproducible example.

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  fluidRow(
    tags$div(id = "ui1", class = 'shiny-html-output shiny-bound-output',
      tags$a(id = "ID1", class = "my-class", href = "#", 'Link 1')
    ),
    uiOutput("ui2")
  )
)

server <- function(input, output) {
  output$ui2 <- renderUI({
    tags$a(id = "ID2", class = "my-class", href = "#", 'Link 2')
  })

  shinyjs::runjs(
  '$(document).ready(function(){
    $(".my-class").click(function(){
      alert($(this).attr("id"));
    });
  });')
}

shinyApp(ui, server)
+4
source share
1 answer

This will work:

library(shiny)
library(shinyjs)

script <- "$('.my-class').click(function(){
alert($(this).attr('id'));
});"

ui <- fluidPage(
  useShinyjs(),
  fluidRow(
    tags$div(id = "ui1", class = 'shiny-html-output shiny-bound-output',
             tags$a(id = "ID1", class = "my-class", href = "#", 'Link 1')
    ),
    uiOutput("ui2")
  )
)

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

  output$ui2 <- renderUI({
    tags$a(id = "ID2", class = "my-class", href = "#", 'Link 2')
  })


  session$onFlushed(function() {
    shinyjs::runjs(script)
  }, once=TRUE)

}

shinyApp(ui, server)
+1
source

Source: https://habr.com/ru/post/1696307/


All Articles