Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use shiny javascript functions?

I want to send data from javascript to R using shiny js function, but is not working. What I have done is a simple example, in which setinputValue send "noone" to "too" input$too

Here is the code:

library(shiny)


ui <- fluidPage(

  HTML("<script>
       $( document ).ready(function() {
       Shiny.setInputValue('too', 'noone');

       });</script>"),


      textOutput("table")


  )


server <- function(input, output) {
 output$table <- renderPrint(input$too)


}

 shinyApp(ui,server)

The js error I get is: Shiny.setInputValue is not a function

like image 298
Iker Avatar asked Jan 04 '19 12:01

Iker


People also ask

What is Shinyjs?

shinyjs lets you perform common useful JavaScript operations in Shiny applications without having to know any JavaScript. Examples include: hiding an element, disabling an input, resetting an input back to its original value, delaying code execution by a few seconds, and many more useful functions.

Does jQuery use shiny?

The jQuery framework is natively included in shiny. jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.


1 Answers

It does not work with $( document ).ready(function(), but with $( document ).on("shiny:sessioninitialized", function(event) {:

library(shiny)  
ui <- fluidPage(      
  HTML('<script>
       $( document ).on("shiny:sessioninitialized", function(event) {
           Shiny.onInputChange("too", "noone");           
       });</script>'),         
  textOutput("table")      
)

server <- function(input, output) {
  output$table <- renderPrint(input$too) 
}

shinyApp(ui,server)

Reason for this is given in the tutorial: You cannot call the function too soon, you need a little time until Shiny is ready to update the input value:

in message.js, we wrapped our code in $(document).ready(function() { ... }. This jQuery function will tell the browser to only run the code inside, once the page, i.e. the Document Object Model (DOM), is ready for JavaScript code to execute. Note that when we activate this code too soon, i.e. before the image is loaded, we cannot yet attach an event handler to it. In other words, here we want to be sure that the image exists before attaching an event handler to it. ```

like image 153
shosaco Avatar answered Oct 05 '22 01:10

shosaco