Does someone know how to highlight the border or the color of a shiny button when it is selected ?
Please find a reproductible example below
library(shiny)
ui <- fluidPage(
actionButton(inputId = "button1", label = "Select red"),
actionButton(inputId = "button2", label = "Select blue"),
plotOutput("distPlot")
)
server <- function(input, output) {
r <- reactiveValues(my_color = "green")
output$distPlot <- renderPlot({
x <- faithful[, 2]
bins <- seq(min(x), max(x))
hist(x, breaks = bins, col = r$my_color)
})
observeEvent(input$button1, {
r$my_color <- "red"
})
observeEvent(input$button2, {
r$my_color <- "blue"
})
}
shinyApp(ui = ui, server = server)
Here is what it get with the code above:
And here is what I would like to get when the button "Select red" is beeing selected (please note that it should highlight the other one when selected) :
If that is not possible, does exist a way to change button color when selected ?
Thanks in advance
You can add/remove CSS classes on the buttons using the shinyjs package. Here I use the btn-primary
class in Bootstrap to make the button blue, but you could add your own styling as well.
library(shiny)
library(shinyjs)
ui <- fluidPage(
useShinyjs(),
actionButton(inputId = "button1", label = "Select red"),
actionButton(inputId = "button2", label = "Select blue"),
plotOutput("distPlot")
)
server <- function(input, output) {
r <- reactiveValues(my_color = "green")
output$distPlot <- renderPlot({
x <- faithful[, 2]
bins <- seq(min(x), max(x))
hist(x, breaks = bins, col = r$my_color)
})
observeEvent(input$button1, {
removeClass("button2", "btn-primary")
addClass("button1", "btn-primary")
r$my_color <- "red"
})
observeEvent(input$button2, {
removeClass("button1", "btn-primary")
addClass("button2", "btn-primary")
r$my_color <- "blue"
})
}
shinyApp(ui = ui, server = server)