Skip to content

Instantly share code, notes, and snippets.

Created March 4, 2021 04:48
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Demo Shiny app illustrating how to communicate between R/Shiny and JavaScript
# Define our function add_class
# Originally written for use in {shinysurveys}
add_class <- function(.id, .class) {
session <- shiny::getDefaultReactiveDomain()
list(input_id = .id, class_name = .class)
# Note, I’m injecting the JavaScript and CSS here for illustrative purposes.
# I typically recommend storing them in separate files for readability
ui <- fluidPage(
# Define the JavaScript
Shiny.addCustomMessageHandler("add_class", function (params) {
$("#" + params.input_id).addClass(params.class_name);
# Define our class "red"
tags$style(".red {color: red;}"),
# Add one div with id “me”
div(id = "me",
# Add another div with id “me-again”
div(id = "me-again",
p("Me, again.")),
actionButton(inputId = "meRed", "Make 'Me' red"),
actionButton(inputId = "meAgainRed", "Make 'Me, again.' red")
server <- function(input, output, session) {
# When the button meRed is clicked add the red class to the “me” div.
observeEvent(input$meRed, {
add_class(.id = "me", .class = "red")
# When the button meAgainRed is clicked add the red class to the “me-again” div.
observeEvent(input$meAgainRed, {
add_class(.id = "me-again", .class = "red")
shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment