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
CodePudding user response:
That's because the table does not exist (is not in the DOM) yet when the script is read. You can do:
$(document).ready(function(){
$('#my_table').on('shiny:value', function(event) {
alert('MSG 1');
});
});
Another way that should work is to put the script at the end of the UI, without tags$head
.