20 Adding custom event handlers

When using onRender() to provide a JS function to be called upon static render of a plotly object, the relevant DOM element (el) has an on() method that accepts a function to be called whenever a plotly.js (or DOM) event occurs on that DOM element. Currently all plotly.js event handlers accept a function with a single argument, and that argument either contains nothing (e.g. "plotly_afterplot", etc) or a single object with all the relevant information about the event (e.g. "plotly_hover", "plotly_selected", etc). Figure 20.1 logs and inspects data (d) emitted during the "plotly_hover", "plotly_click", and "plotly_selected" events. The object emitted for these events includes a key, named points, with information tying the selection back to the input data. The points key is always an array of object(s) where each object represents a different data point. This object contains any supplied customdata, the relevant x/y location, and a reference back to the input data.

library(htmlwidgets)
plot_ly(mtcars, x = ~wt, y = ~mpg) %>%
  onRender("
    function(el) { 
      el.on('plotly_hover', function(d) { 
        console.log('Hover: ', d); 
      });
      el.on('plotly_click', function(d) { 
        console.log('Click: ', d);
      });
      el.on('plotly_selected', function(d) { 
        console.log('Select: ', d); 
      });
    }
  ")

FIGURE 20.1: Inspecting event data for hover, click, and selected events. If a click or hover event does not derive from a statistical aggregation (e.g., boxplot, histogram, etc), the points array is of length 1; otherwise, the length corresponds to how many input values are represented in the selection. In Chrome, when you log an object to the console, you can click on a link to the JS source function where you can then set breakpoints. For the interactive, see https://plotly-r.com/interactives/console-log-event.html