clipboard.js in Shiny application

397 Views Asked by At

I am trying to copy to the clipboard 'Clipboard copied !' when a button is clicked using clipboard.js.

Nothing is copied, with the JS error: Uncaught TypeError: Cannot read property 'addEventListener' of null.

library(shiny.semantic)

ui <- semanticPage(
    tags$head(
        tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.4/clipboard.min.js"),
        tags$script(HTML("new ClipboardJS('.clipboardButton');"))
    ),
    
    action_button(input_id="myButton",
                  class = "clipboardButton",
                  label = "Click Me !",
                  `data-clipboard-text` = "Clipboard copied !"
    ),
    text_input("text",
               placeholder="paste here to check"
    )
)

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

shinyApp(ui, server)
1

There are 1 best solutions below

2
Stéphane Laurent On BEST ANSWER

You have to add a $(document).ready:

  tags$head(
    tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.4/clipboard.min.js"),
    tags$script(HTML(
      "$(document).ready(function(){new ClipboardJS('.clipboardButton');});"
    ))
  ),