Skip to content

Instantly share code, notes, and snippets.

@jdtrat
Created March 4, 2021 04:48
Show Gist options
  • Save jdtrat/9dcef57687772742e7227cbd373e20aa to your computer and use it in GitHub Desktop.
Save jdtrat/9dcef57687772742e7227cbd373e20aa to your computer and use it in GitHub Desktop.
Demo Shiny app illustrating how to communicate between R/Shiny and JavaScript
library(shiny)
# Define our function add_class
# Originally written for use in {shinysurveys}
add_class <- function(.id, .class) {
session <- shiny::getDefaultReactiveDomain()
session$sendCustomMessage(
"add_class",
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
tags$script('
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",
p("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