0

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")
    )
    
  })
  
})

1 Answer 1

2

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")
    )
  })
})
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a ton. Your second solution works for me. Just a question - console.log(evt.target) does not return anything in console? any reference for me please to read in detail about document event handler
I removed that. I forgot it was there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.