'Shiny Javascript Events not working with $(#id) jQuery selector

In the documentation from RStudio about javascripts events in shiny https://shiny.rstudio.com/articles/js-events.html, there is this example for the shiny:value event :

$('#foo').on('shiny:value', function(event) {
  // append a character string to the output value
  event.value += ' Oh that is nice!';
});

// use event.target to obtain the output element
$(document).on('shiny:value', function(event) {
  // cancel the output of the element with id 'foo'
  if (event.target.id === 'foo') {
    event.preventDefault();
  }
});

and it says :

Since these events are triggered specifically on an output element, you may add the listener on the output element instead of on the document, although the latter also works, e.g.

but when I try to use the first method in my shiny app, it doesn't seems to work.

For example if you run the app bellow, only the method with the $(document) selector is working and triggers a message.

library(shiny)

ui <- fluidPage(
  tags$head(
    tags$script(
      "$('#my_table').on('shiny:value', function(event) {
        alert('MSG 1');
      });"
    ), 
    tags$script(
      "$(document).on('shiny:value', function(event) {
        if (event.target.id === 'my_table') {
          alert('MSG 2');
        }
      });"
    )
  ),
  
  sliderInput("my_slider", "Rows", 1, 20, 1),
  tableOutput("my_table")
)

server <- function(input, output, session) {
  output$my_table <- renderTable(iris[1:input$my_slider, ])
}

shinyApp(ui, server)

I suppose that I'm missing something as in the documentation, it says that the 2 method should work. Any help appreciated, thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source