Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

onRender

Execute custom JavaScript code after rendering


Description

Use this function to supplement the widget's built-in JavaScript rendering logic with additional custom JavaScript code, just for this specific widget object.

Usage

onRender(x, jsCode, data = NULL)

Arguments

x

An HTML Widget object

jsCode

Character vector containing JavaScript code (see Details)

data

An additional argument to pass to the jsCode function. This can be any R object that can be serialized to JSON. If you have multiple objects to pass to the function, use a named list.

Details

The jsCode parameter must contain valid JavaScript code which when evaluated returns a function.

The function will be invoked with three arguments: the first is the widget's main HTML element, and the second is the data to be rendered (the x parameter in createWidget). The third argument is the JavaScript equivalent of the R object passed into onRender as the data argument; this is an easy way to transfer e.g. data frames without having to manually do the JSON encoding.

When the function is invoked, the this keyword will refer to the widget instance object.

Value

The modified widget object

See Also

onStaticRenderComplete, for writing custom JavaScript that involves multiple widgets.

Examples

## Not run: 
library(leaflet)

# This example uses browser geolocation. RStudio users:
# this won't work in the Viewer pane; try popping it
# out into your system web browser.
leaflet() %>% addTiles() %>%
  onRender("
    function(el, x) {
      // Navigate the map to the user's location
      this.locate({setView: true});
    }
  ")


# This example shows how you can make an R data frame available
# to your JavaScript code.

meh <- "&#x1F610;";
yikes <- "&#x1F628;";

df <- data.frame(
  lng = quakes$long,
  lat = quakes$lat,
  html = ifelse(quakes$mag < 5.5, meh, yikes),
  stringsAsFactors = FALSE
)

leaflet() %>% addTiles() %>%
  fitBounds(min(df$lng), min(df$lat), max(df$lng), max(df$lat)) %>%
  onRender("
    function(el, x, data) {
      for (var i = 0; i < data.lng.length; i++) {
        var icon = L.divIcon({className: '', html: data.html[i]});
        L.marker([data.lat[i], data.lng[i]], {icon: icon}).addTo(this);
      }
    }
  ", data = df)

## End(Not run)

htmlwidgets

HTML Widgets for R

v1.5.3
MIT + file LICENSE
Authors
Ramnath Vaidyanathan [aut, cph], Yihui Xie [aut], JJ Allaire [aut], Joe Cheng [aut], Carson Sievert [aut, cre] (<https://orcid.org/0000-0002-4958-2844>), Kenton Russell [aut, cph], Ellis Hughes [ctb], RStudio [cph]
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.