Reputation: 2033
I am using jQuery (jQuery Core 2.1.4) to develop part of my Shiny app. In addition, I am using the new plotly
package to render the plots. jQuery works perfectly on its own and plotly
too; however when using both, the plots from plotly
dissapear. Calling jQuery seems to be the cause.
Is there a work-around that allows to use jQuery and
plotly
(specificallyggplotly
) in the same Shiny App?
Here is an example. I am aware this example does not need the jQuery but is only to illustrate how plotly
plots dissapear when including jQuery (uncomment the line #tags$head(tags$script(src='http://code.jquery.com/jquery-2.1.4.js')),
to include it):
#Call the required libraries
library(shiny)
library(plotly)
library(ggplot2)
#Server to output plot
server <- shinyServer(function(input, output) {
output$plotlyout <- renderPlotly({
#Create random points
x <- rnorm(100)
y <- rnorm(100)
#Set to data frame
dats <- as.data.frame(cbind(x,y))
#Plot them in plotly
ggplotly(ggplot(dats) + geom_point(aes(x = x, y = y)))
})
})
#Shiny plot
ui <- shinyUI(
#One page with main Panel
fluidPage(
#Uncomment this to see how Jquery ruins everything
#tags$head(tags$script(src='http://code.jquery.com/jquery-2.1.4.js')),
#Panel for plot
mainPanel(
#Output plot
plotlyOutput("plotlyout")
)
)
)
shinyApp(ui = ui, server = server, options = list(launch.browser = TRUE))
Thanks!
Upvotes: 5
Views: 874
Reputation: 26313
Solution: You need to use JQuery's noconflict(). Add tags$head(tags$script("$.noConflict(true);")),
after the line loading jquery.
Explanation: JQuery already gets loaded by default by Shiny. You can see this by viewing the source of the page of any Shiny app, and you'll see that it loads jquery. When I ran your app and looked at the JavaScript console for errors, I was getting strange errors that suggested that something with JQuery isn't working right. So I thought "hmm jquery is definitely loaded. It's actually loaded twice. But it's not working when I load it twice. Let's Google that!". So if you Google for how to load jquery twice on one page, you'll see lots of answers saying to use noconflict(). Adding it after your line of jquery seems to do the trick.
Upvotes: 6