I have a small application in shiny:
library(shiny)
ui <- fluidPage(
#htmlOutput("d"),
tags$p(id = 'g', class = 'newClass', 'This is a paragraph'),tags$p(id = "demo"),
tags$script(HTML("var tit = document.getElementById('g');tit.onclick = function (){document.getElementById('demo').innerHTML = Date()}"))
)
server <- function(input, output, session) {
}
shinyApp(ui, server)
This application is using javascript. When the user clicks on the sentence, the date displays. But the date is passed in the UI section itself.
My question is, Can we not pass the variable from server to UI here? For example,
we create Var1 <- Sys.Date()
in server section. Now I need to pass Var1 to UI in place of Date()
. Is it possible?
I have tried with below approach. But failed. Anyone please help since I do not have much knowledge on Javascript
library(shiny)
library(shinyjs)
ui <- fluidPage(
tags$p(id = 'g', class = 'newClass', 'This is a paragraph'),tags$p(id = "demo"),
tags$script(HTML(
"var tit = document.getElementById('g');
var insertion_text = Shiny.addCustomMessageHandler('bla',function(message) {return(message)};
tit.onclick = function (){document.getElementById('demo').innerHTML = insertion_text}"
))
)
server <- function(input, output, session) {
observe({
session$sendCustomMessage(type = 'bla', message = Sys.Date())
})
}
shinyApp(ui, server)
2
Answers
Thanks for the answer. However, I tried below that I thought a simple approach and it is working
WHat you say ?
It is possible to pass dynamic variable from server to UI.
With
shinyjs::runjs()
With R
session$sendCustomMessage()
and jsShiny.addCustomMessageHandler()
Read also
$(document).on('shiny:connected', function(event) { ... });
when the page is partially loaded but Shiny not yet.edited after comment