Created
October 1, 2021 13:06
-
-
Save MayaGans/b35d0ba95906f1928c4062d6b3a2585e to your computer and use it in GitHub Desktop.
toggle class color
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(shiny) | |
# note that the cells we want to toggle have a class called changes-color | |
df <- data.frame( | |
a = c( | |
"<div class='changes-color'>A</div>", | |
"<div>B</div>", | |
"<div class='changes-color'>C</div>" | |
) | |
) | |
ui <- fluidPage( | |
actionButton("chg_color", 'Change Color!'), | |
DT::dataTableOutput("table"), | |
# javascript functions to actually toggle the classes | |
tags$script(HTML( | |
" | |
Shiny.addCustomMessageHandler('add_class', function (new_class) { | |
$('.changes-color').addClass(new_class) | |
}); | |
Shiny.addCustomMessageHandler('remove_class', function (new_class) { | |
$('.changes-color').removeClass(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$table <- DT::renderDataTable({ | |
datatable( | |
df, | |
escape = FALSE, | |
rownames = FALSE | |
) | |
}) | |
# trigger running the add class function in JS | |
add_class <- function(new_class) { | |
session <- shiny::getDefaultReactiveDomain() | |
session$sendCustomMessage("add_class", new_class) | |
} | |
# trigger running the remove class function in JS | |
remove_class <- function(new_class) { | |
session <- shiny::getDefaultReactiveDomain() | |
session$sendCustomMessage("remove_class", new_class) | |
} | |
# put an observe event on the button | |
# so we can toggle between the add and remove class functions | |
observeEvent(input$chg_color, { | |
if (!input$chg_color %% 2 == 0) { | |
add_class("active") | |
} else { | |
remove_class("active") | |
} | |
}) | |
} | |
shinyApp(ui, server) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment