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) });
}
")