Use JQuery/JS to change colour of shiny infobox depending on its value

Viewed 26

I want to be able to use JS or JQuery to change the css of an infoboxOutput based on the value contained within it. I am looking for something native (so in tags$script or an external js file) that can be done without using any additional libraries.

Please see my example below which isnt working.

library(shiny)
library(shinyWidgets)
library(shinydashboard)

ui <- fluidPage(
  useShinydashboard(),
  textInput("number", "enter num", value = 10),
  infoBoxOutput("info", width = 4),
  tags$script('
              $("#info .info-box-content .info-box-number").on("change",function(e){
               let valueCheck = Number($("#info .info-box .info-box-content .info-box-number").text()) < 0;
               console.log(valueCheck);
               if(valueCheck){
                 $("#info .info-box").removeClass("bg-red").css("background-color", "black").css("color", "white");
                }
                else {
                $("#info .info-box").removeClass("bg-red").css("background-color", "white").css("color", "black");
                });
              })
              ')
)


server <- function(input, output, session){
  output$info <- renderInfoBox({
    req(input$number)
    
    infoBox(title = "",
            value = input$number,
            subtitle = "hello",
            color = "red",
            fill = TRUE)
    
    
  })
}


shinyApp(ui, server)
1 Answers

Couple of things:

  1. wrapped script in HTML() so the symbols stays intacted (e.g. < would be changed to &lt;
  2. changed from #info to #number since it is an id of a input you might want to track
  3. fixed brakcets typo in script
library(shiny)
library(shinyWidgets)
library(shinydashboard)

ui <- fluidPage(
    useShinydashboard(),
    textInput("number", "enter num", value = 10),
    infoBoxOutput("info", width = 4),
    tags$script(HTML('
              $("#number").on("change",function(e){
               let valueCheck = Number($("#info .info-box .info-box-content .info-box-number").text()) < 0;
               console.log(valueCheck);
               if(valueCheck){
                 $("#info .info-box").removeClass("bg-red").css("background-color", "black").css("color", "white");
                }
                else {
                $("#info .info-box").removeClass("bg-red").css("background-color", "white").css("color", "black");
                }
                });
              '))
)


server <- function(input, output, session){
    output$info <- renderInfoBox({
        req(input$number)
        
        infoBox(title = "",
                value = input$number,
                subtitle = "hello",
                color = "red",
                fill = TRUE)
        
        
    })
}


shinyApp(ui, server, options = list(launch.browser = T))
Related