Reputation: 1372
I want to understand how we can interact server section of code with pure JS (or Jquery). I prepared two examples - Basically I want to hide h4( ) on clicking of button by user. First example works as expected but second one does not work as h4() is in renderUI( ) in server. I know this can be solved via observeEvent or shinyJS package but I am more interested to make it work with pure JS not running JS code in server.
Example 1
library(shiny)
ui <- fluidPage(
fluidRow(
h4("Testing"),
actionButton("Disable", "Disable Element"),
tags$script("
$(document).ready(function() {
$('#Disable').click(function(){
$('h4').css('display', 'none');
});
})")
)
)
shinyApp(ui, server = function(input, output) { })
Example 2
ui <- fluidPage(
fluidRow(
h4("Testing"),
uiOutput("myfun"),
tags$script("
$(document).ready(function() {
$('#Disable').click(function(){
$('h4').css('display', 'none');
});
})")
)
)
shinyApp(ui, server = function(input, output) {
output$myfun <- renderUI({
tagList(
actionButton("Disable", "Disable Element")
)
})
})
Upvotes: 0
Views: 81
Reputation: 206596
One option is to add an onclick event to the button itself.
ui <- fluidPage(
fluidRow(
h4("Testing"),
uiOutput("myfun"),
tags$script("hideH4 = function() {$('h4').css('display', 'none');}")
)
)
shinyApp(ui, server = function(input, output) {
output$myfun <- renderUI({
tagList(
actionButton("Disable", "Disable Element", onclick="hideH4()")
)
})
})
Or add a document event hadler for the click and check the ID
ui <- fluidPage(
fluidRow(
h4("Testing"),
uiOutput("myfun"),
tags$script("
$(document).click(function(evt) {
if (evt.target.id=='Disable') {
$('h4').css('display', 'none');
}})")
)
)
shinyApp(ui, server = function(input, output) {
output$myfun <- renderUI({
tagList(
actionButton("Disable", "Disable Element")
)
})
})
Upvotes: 2