7

I want to use jquery UI with shiny (not using shinyjqui library). It works perfect when I have a layer and tried to move it using jqueryUI, but when this layer is dynamically generated using insertUI, then, it doesn´t work.

Here is the code:

library(shiny)

ui <- fluidPage(theme = "style.css",
            tags$script(src = "jquery-ui.js"),
            tags$script(src = "script2.js"),
            actionButton("add","Add layer"),
            div(class="aux"),
            div(id="works",style="width:300px;height:200px;background:red"))



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

    observeEvent(input$add,{
    insertUI(
      selector = ".aux",
      where="afterEnd",
      ui  = div(id=paste0("new",input$add),style="width:300px;height:200px;background:blue")

    )


  })






}
shinyApp(ui, server)

And the js script

  $( function() {


    $("#works").draggable();
    $("#new1").draggable();


  });

Thanks!

1 Answer 1

9

That's because #new1 does not exist at the start-up. You have to execute the javascript code after it have been created, with shinyjs::runjs for example. And use immediate=TRUE in insertUI.

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  tags$head(
    tags$script(src = "jquery-ui/jquery-ui.min.js"),
    tags$script("$(function() {
                    $('#works').draggable();
                })")
  ),
  actionButton("add","Add layer"),
  div(class="aux"),
  div(id="works",style="width:300px;height:200px;background:red"))

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

  observeEvent(input$add,{
    insertUI(
      selector = ".aux",
      where="afterEnd",
      ui = div(id=paste0("new",input$add), style="width:300px;height:200px;background:blue"),
      immediate = TRUE
    )
    runjs("$('#new1').draggable();")
  })

}

shinyApp(ui, server)

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

Works perfect. Thanks!
I'm not able to get this to work. Perhaps something has changed.
@GiovanniColitti did you download the jquery ui library and place it in the same directory as your shiny app? also you can do 'ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js' as the src in the first tags$script() instead of 'jquery-ui/jquery-ui.min.js'.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.