6.1 Custom behavior via JavaScript

The section on linking views with shiny shows how to acquire data tied to plotly.js events from a shiny app. Since shiny adds a lot of additional infrastructure, plotly also provides a way to link views without shiny, but this definitely does not encompass every type of interactivity. Thankfully the htmlwidgets package provides a way to invoke a JavaScript function on the widget element (after it is done rendering) from R via the onRender() function (Vaidyanathan et al. 2016). The JavaScript function should have at least two arguments: (1) the DOM element containing the htmlwidget (el) and (2) the data passed from R (x). This enables, for instance, the ability to author custom behavior tied to a particular plotly.js event. Figure ?? uses onRender() to open a relevant Google search upon clicking a point.

library(plotly)
library(htmlwidgets)

mtcars$url <- paste0("http://google.com/#q=", rownames(mtcars))

p <- plot_ly(mtcars, x = ~wt, y = ~mpg) %>%
  add_markers(text = rownames(mtcars), customdata = ~url) %>%
  onRender("
    function(el, x) {
      el.on('plotly_click', function(d) {
        var url = d.points[0].customdata;
        window.open(url);
      });
    }
  ")

References

Vaidyanathan, Ramnath, Yihui Xie, JJ Allaire, Joe Cheng, and Kenton Russell. 2016. Htmlwidgets: HTML Widgets for R. https://CRAN.R-project.org/package=htmlwidgets.