Customize the colors of individual checkboxes within a checkboxGroupInput in R Shiny

I really want to customize the color of each individual checkbox in my checkboxGroupInput, moving away from the typical shiny blue. After doing some research, I came across a code snippet on Stack Overflow that changes the font color but not the checkboxes themselves.

library("shiny")

ui <- fluidPage(
  checkboxGroupInput(
    inputId = "my_cbgi",
    label = "Choose Something", 
    choiceNames = list(
      tags$span("A", style = "color: red;"),
      tags$span("B", style = "color: red;"), 
      tags$span("C", style = "color: blue;"), 
      tags$span("D", style = "font-weight: bold;")
    ),
    choiceValues = c("A", "B", "C", "D")
  )
)

server <- function(input, output) {

}

shinyApp(ui = ui, server = server)

I'm wondering if there is a way to tweak this code to actually change the colors of the checkboxes themselves rather than just the text. Any insights would be greatly appreciated!

Answer №1

To utilize the prettyCheckboxGroup from the shinyWidgets package, you can follow these steps:

library(shiny)
library(shinyWidgets)

items <- c("Apple", "Banana", "Orange")

CSS <- "
/* CSS for customized labels */
.pretty input[value=Apple]~.state span {
  color: red;
  font-weight: bold;
}
/* Styling for checkboxes */
.pretty input[value=Apple]~.state label:after, 
.pretty input[value=Apple]~.state label:before {
  background-color: red;
}
.pretty input[value=Banana]~.state label:after, 
.pretty input[value=Banana]~.state label:before {
  background-color: green;
}
.pretty input[value=Orange]~.state label:after, 
.pretty input[value=Orange]~.state label:before {
  background-color: blue;
}
/* Style for checked checkboxes */
.pretty.p-default input:checked~.state label:after {
  background-color: yellow !important;
}
"

ui <- fluidPage(
  tags$head(tags$style(HTML(CSS))),
  h1("Greetings"),
  prettyCheckboxGroup("fruits", label="Choose fruits", 
                      choiceNames = items, choiceValues = items, 
                      selected = items),
  verbatimTextOutput("choice")
)

server <- function(input,output,session){
  output$choice <- renderText(input$fruits)
}

shinyApp(ui, server)

Answer №2

Answering your question briefly, customizing checkboxes in HTML and CSS is not a straightforward task. If you're hesitant to directly modify the code, it's advisable not to invest time in this.

In creating the checkbox container, checkBoxGroupInput utilizes shiny:::generateOptions internally. A peek into the source reveals that altering the style of individual checkboxes isn't a simple feat as they all share the same class="checkbox" by default (a referenced response only covers setting a universal style for all choices).

The only solution I can suggest is directly injecting raw HTML into your UI. However, even this method gets complex because you cannot apply styles (like borders) directly to the checkbox element to influence its display, as explained in the aforementioned response. While exploring CSS myself, it seems that building new HTML checkboxes from scratch and layering them over the default ones might be the workaround (although hiding the default checkboxes successfully has proven challenging).

Below is a functional example catered to your requirements with its corresponding output displayed after the code snippet. Each scenario employs distinct wrappers (.my_checkBox_red, .my_checkBox_blue, and .my_checkBox_grey). There may exist a more efficient approach by just adjusting the relevant styles (color:, background-color:), but I haven't cracked this puzzle yet. Another enhancement could involve automating the lengthy HTML string generation, although I lack the bandwidth to tackle this at present. For those interested, delving into the shiny function checkBoxGroupInput or shiny:::generateOptions serve as great starting points, or build a personalized function with utilities like sprintf, paste, and so forth.

Hope this sheds some light on your query!

(function(){
  var themeSheet = document.createElement("style");
  themeSheet.type = "text/css";
  
  var cssString = '.my_checkBox input[type="checkbox"]+span {margin-left:10px};'
      + ' .my_checkBox input[type="checkbox"]:checked~label {font-weight:bold;}';
    
  themeSheet.innerHTML = cssString;
  document.head.appendChild(themeSheet);
}());

https://i.sstatic.net/7uc20.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generating a zip file with password encryption in the R programming language

Attempted to create a password protected zip file in R using the code below but it did not work and no error was shown. zip('file.zip', files = 'file.pdf', flags = paste("--password", 'pwd123')) Seeking assistance ...

Angular disrupts the functionality of jQuery slideshow

While working on this template, I encountered issues with the functionality after integrating Angular into the application. Although I managed to fix most of them, I'm facing difficulty getting the slideshow to function properly. Here is the HTML cod ...

showcasing a set of div elements by using forward and backward buttons

I am dealing with 5 divs that have text content inside. To navigate through each div, I have implemented a back and next button system. <a href="" class="back-btn off">Back</a> | <a href="" class="next-btn">Next</a> <div class ...

Unable to set items as sticky within mat-tabs

Is there a way to make my image stick in place using the following CSS code? position: -webkit-sticky; position: sticky; top: 1px; I have tried implementing it but haven't been successful. HTML: <mat-tab-group class="user-tabs" (selectedTa ...

Move the container all the way to the left

On my page, I have a grey section with the heading 'Start Analysis' that needs to be shifted to the left along with all its contents. How can this be achieved? The HTML code for the section is as follows: <!DOCTYPE html> <html lang="en ...

Avoid having the browser automatically move focused elements that are navigated to using the tab key

When moving through form elements or anchors using the tab key (and shift + tab), the browser automatically scrolls to the focused element. If the element is not visible due to being part of overflow content with a hidden overflow setting, the container&ap ...

Issues regarding the animation and hover effects of a button

I have successfully created a button with an animation on my webpage. The button pops up after 3-4 seconds, and when the user hovers over it, it widens. However, I'm encountering an issue where the pop-up animation restarts every time the button is ho ...

Display a horizontal progression indicator during the page download process

Occasionally, website pages may take a while to download without the user even realizing it. This can be problematic if the user clicks on an image or button with an event handler attached, as it may break the page functionality. To address this issue, I ...

In IE11, the letter type list with the style of lower-alpha no longer displays proper indentation

When viewing on IE11, the list in lower-alpha style (list-style-type: lower-alpha) is missing indentation. However, the indentation remains intact when viewed on Chrome, Edge, and Firefox browsers. The code snippet below showcases some of the CSS styles be ...

The presence of the `ng-scope` class is creating problems within the user interface

Encountering an issue where the CSS class ng-scope is causing disruption to the user interface. The goal is to set the height of the toDoListRow div to 70%. However, this only works if the ng-scope class is defined with a height of 100%, leading to unexpe ...

Exploring the similarities and differences between the precise and estimated versions of the Cumulative Distribution Function using the R programming command ec

Seeking to calculate both the precise and approximate Cumulative Distribution Function for this particular density: f(x)= U(x;-1,2)/2 + U(x;0,1)/2 where U(.;a,b) represents the uniform density function within the range [a,b]. While I am able to compute t ...

employing logical operators in conjunction with characters

I have a data frame with three thousand rows and I want to create a new column that contains zeros or ones based on the value in another column. I wrote a function that checks the value in a specific column, and if it matches a certain word, it assigns a ...

Having trouble with Vue.js implementation of Bootstrap tab navigation?

I am currently working on a vue.js application that consists of 2 routed components. I recently attempted to integrate a bootstrap tab navigation into the first component, but unfortunately, the tab contents are not being properly displayed. <templat ...

CSS HTML parent div cannot contain image properly

Creating a website using Bootstrap: <div class="row padding_zero"> <div class="col section px-0"> <img class="img-trans padding_zero" src="./svg/clouds-00.svg" style="margin-top: -150px& ...

Is it possible to interpret the information in a text file as a query?

In my work with R, I am looking to simply extract the text from a file and store it in a variable using the following code: query <- read_file_contents('biglongquery.sql') This method allows me to keep large queries separate from the main R ...

The combination of two tags can create a powerful and impactful presence

My task is to place two <h3> tags in the same line or paragraph. <h3>This is the first paragraph. </h3> <h3>This is the second paragraph.</h3> I would like the output to look like this: This is the first paragraph. This is Se ...

Utilize a custom attribute in Bootstrap 4 tooltips instead of the standard "title" attribute to define the text displayed in

For my application, I'm utilizing Bootstrap 4 along with tooltips. My objective is to toggle the tooltips individually and only display them upon clicking. The following code allows me to achieve this: <input type="text" id="name" class="form-cont ...

Utilize the design elements stored in the database within Django

I have a style stored in my database and I want to use it in a template, but I'm not sure how to do it. models.py class Post(models.Model): # ... body = models.TextField() # HTML style = models.TextField() # CSS # ... views.py ( ...

Problem with displaying fonts in web browsers

I decided to create a React App using the Material UI library, but I wanted to customize it by changing the default font from Roboto to Overpass. I successfully imported the fonts using their library. <link rel="preconnect" href="https:// ...

Include a prefix to each CSS selector in the imported CSS file

In my React project using create-react-app: index.js ... import "@mock/style/css/mock.css"; I am looking to modify all css selectors in the above file by adding a prefix. What is the most effective way to accomplish this task? Should I utilize ...