Skip to content

Instantly share code, notes, and snippets.

@MayaGans
Created October 7, 2021 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MayaGans/989da07eee2423b4f3d49eb11038a75d to your computer and use it in GitHub Desktop.
Save MayaGans/989da07eee2423b4f3d49eb11038a75d to your computer and use it in GitHub Desktop.
toggle color, multiple tables
library(shiny)
# note that the cells we want to toggle have a class called changes-color
df1 <- data.frame(
a = c(
"<div class='changes-color'>A</div>",
"<div>B</div>",
"<div class='changes-color'>C</div>"
)
)
df2 <- data.frame(
a = c(
"<div>A</div>",
"<div class='changes-color'>B</div>",
"<div>C</div>"
)
)
ui <- fluidPage(
actionButton("chg_color1", 'Change Table 1 Color'),
actionButton("chg_color2", 'Change Table 2 Color'),
DT::dataTableOutput("table1"),
DT::dataTableOutput("table2"),
# javascript functions to actually toggle the classes
tags$script(HTML(
"
Shiny.addCustomMessageHandler('add_class', function (params) {
$('#' + params.table_id).find('.changes-color').addClass(params.new_class)
});
Shiny.addCustomMessageHandler('remove_class', function (params) {
$('#' + params.table_id).find('.changes-color').removeClass(params.new_class)
});
"
)),
# css when the cell has the active class itll be red
# we can use whatever class name we want here really
tags$style(HTML("
.active{
color: red;
font-weight: 800;
}"))
)
server <- function(input, output, session) {
output$table1 <- DT::renderDataTable({
datatable(
df1,
escape = FALSE,
rownames = FALSE
)
})
output$table2 <- DT::renderDataTable({
datatable(
df2,
escape = FALSE,
rownames = FALSE
)
})
# trigger running the add class function in JS
add_class <- function(.id, .class) {
session <- shiny::getDefaultReactiveDomain()
session$sendCustomMessage("add_class",
list(table_id = .id,
new_class = .class)
)
}
# trigger running the remove class function in JS
remove_class <- function(.id, .class) {
session <- shiny::getDefaultReactiveDomain()
session$sendCustomMessage("remove_class",
list(
table_id = .id,
new_class = .class
)
)
}
# put an observe event on the button
# so we can toggle between the add and remove class functions
observeEvent(input$chg_color1, {
if (!input$chg_color1 %% 2 == 0) {
add_class("table1", "active")
} else {
remove_class("table1", "active")
}
})
observeEvent(input$chg_color2, {
if (!input$chg_color2 %% 2 == 0) {
add_class("table2", "active")
} else {
remove_class("table2", "active")
}
})
}
shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment