Using only Javascript commands in shiny

I am trying use only only javascript to plot a graph in shiny. Can anyone help me in achieving this below

library(shiny)

ui <- fluidPage(
#htmlOutput("d"),
tags$p(id = 'g', class =  'newClass',  'This is a plot'),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 is an application when the user clicks on the content, the date displays below

Now, can we change this, so that when the user click on the content, a plot plot_ly(iris, x = ~Species, y = ~Petal.Length) should appear. I know we can achieve somehow using shiny functionality (using button). But Wanted to know if we can do this using only JS.

Hello,

This was a fun one to think about :slight_smile:
I'm curious why you would want to use it, but I got it to work with some hacks

library(shiny)
library(plotly)
library(htmlwidgets)

if(!file.exists("www/my_plotly_plot.html")){
  p <-plot_ly(iris, x = ~Species, y = ~Petal.Length)
  saveWidget(p, file = "www/my_plotly_plot.html", selfcontained = TRUE)
}


ui <- fluidPage(
  #htmlOutput("d"),
  tags$p(id = 'g', class =  'newClass',  'This is a plot'),tags$p(id = "demo"),
  tags$iframe(src="my_plotly_plot.html", width = "500px", height = "200px", id = "myPlot", style = "display: none;"),
  tags$script(HTML("var tit = document.getElementById('g');tit.onclick = function (){document.getElementById('myPlot').style.display = 'block'};")),

)

server <- function(input, output, session) {

}

shinyApp(ui, server)

Hope this helps,
PJ

1 Like