4

I have a shiny app with UI entirely written in HTML and I need the HTML element with specific id to be hidden/shown, depending on whether the data meets specific conditions.

Below is a simplified version of what I already have, I used ShinyJS, but functions show() and hide() don't do anything in my app. What do I need to do in order to make this work? If it's not possible with ShinyJS, what's the other way I can show/hide html elements in a shiny app? Thanks in advance.

app.R

server <- function(input, output) {

  library(shinyjs)
  useShinyjs(html = TRUE)

  data <- reactive({
    return("abcde")
  })
  
  observe({
    if ( data() == "abcde"  ) {
      hide("visibility-area")
    } else {
      show("visibility-area")
    }
  })

  output$some-output <- renderPrint({
    cat(data())
  })
  
}

shinyApp(ui = htmlTemplate("www/index.html"), server)

www/index.html

<!DOCTYPE html>
<html>
<head>
  <script src="shinyjs/inject.js"></script>
  <script src="shared/jquery.js" type="text/javascript"></script>
  <script src="shared/shiny.js" type="text/javascript"></script>
  <link rel="stylesheet" type="text/css" href="shared/shiny.css"/>
  <title>test</title>
</head>
<body>
    <div id="visibility-area">
      <p><span id="some-output" class="shiny-text-output"></span></p>
    </div>
</body>
</html>

global.R

shiny::addResourcePath("shinyjs", system.file("srcjs", package = "shinyjs"))
Ewelina Luczak
  • 379
  • 4
  • 13

1 Answers1

2

When running the provided sample, I see the following error message in the javascript console:

Uncaught ReferenceError: Shiny is not defined

which is coming from the shinyjs/inject.js scropt. The problem is that script is trying to call a method on the Shiny object, but that object doesn't exist yet. You've loaded that file before you've loaded the shared/shiny.js file which defines that object. Changing the order of the includes in our <head> seems to do the trick. (I just moved it last)

<head>
  <script src="shared/jquery.js" type="text/javascript"></script>
  <script src="shared/shiny.js" type="text/javascript"></script>
  <link rel="stylesheet" type="text/css" href="shared/shiny.css"/>
  <script src="shinyjs/inject.js"></script>
  <title>test</title>
</head>
MrFlick
  • 195,160
  • 17
  • 277
  • 295