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 6.1 uses onRender() to open a relevant Google search upon clicking a point.

search <- paste0(
  "http://google.com/#q=", curl::curl_escape(rownames(mtcars))
plot_ly(mtcars, x = ~wt, y = ~mpg, color = ~factor(vs)) %>%
  add_markers(text = ~search, hoverinfo = "x+y") %>%
    function(el, x) {
      el.on('plotly_click', function(d) {
        // d.points is an array of objects which, in this case,
        // is length 1 since the click is tied to 1 point.
        var pt = d.points[0];
        var url = pt.data.text[pt.pointNumber];
        // DISCLAIMER: this won't work from RStudio

Figure 6.1: Using onRender() to register a JavaScript callback that opens a google search upon a ‘plotly_click’ event.


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