Changing the CSS class of a div using Shiny

One of the features in my Shiny app is a select menu which is represented in the code snippet below.

selectInput(
        "mySelectMenu",
        "",
        c(1,2),
        selected = NULL,
        multiple = FALSE
      )

I have set up actions to be triggered on this element as shown below

observeEvent(input$mySelectMenu,{
    currentIndividual<-as.numeric(input$mySelectMenu)
    toggleFunction(currentIndividual)
},ignoreInit=TRUE)

Upon inspecting the element, I can view the div containing the dropdown content. The HTML structure appears like this

<div class="selectize-dropdown-content">
   <div data-value="1" data-selectable="" class="option selected">318_2007</div>
   <div data-value="2" data-selectable="" class="option">320_2007</div>
   <div data-value="3" data-selectable="" class="option">321_2007</div>
   <div data-value="4" data-selectable="" class="option">344_2009</div>
   <div data-value="5" data-selectable="" class="option">346_2009</div>
   <div data-value="6" data-selectable="" class="option">355_2009</div>
</div>

The visual representation can be seen in the image at this link: https://i.sstatic.net/ojo2o.jpg

In certain scenarios, I want to change the appearance of specific menu items. For example, I want the div with 'data-value="2"' to have BOLD RED text. How can I add or remove the CSS class (.menuItemInactive) from this specific div? I am already utilizing shiny.js and am open to using it or any other appropriate package for this customization.

.menuItemInactive{
    font-weight:bold;
    color:red;
}

Answer №1

If you want to change the appearance of a dropdown based on user selection in a Shiny app, you can utilize the shinyjs package along with the runjs method. By monitoring the selectInput choices, you can dynamically adjust the css styles of the dropdown.

library(shiny)
library(shinydashboard)
library(shinyjs)

ui <- fluidPage(
  shinyjs::useShinyjs(),
  tabItem(tabName = "comp",
          fluidRow(
            selectInput("mySelectMenu", "",c(1,2,3),selected = NULL, multiple = FALSE
            )))
)

server <- function(input, output, session) { 
  observeEvent(input$mySelectMenu,{
    currentIndividual<-as.numeric(input$mySelectMenu)
    # toggleFunction(currentIndividual)
  },ignoreInit=TRUE)

  observeEvent(input$mySelectMenu, {
    if (input$mySelectMenu == 1) {
      runjs(paste0('$(".selectize-input").css({"color": "red", "font-weight": "bold"})'))
    }
    if (input$mySelectMenu == 2) {
      runjs(paste0('$(".selectize-input").css({"color": "blue", "font-weight": "bold"})'))
    }
    if (input$mySelectMenu == 3) {
      runjs(paste0('$(".selectize-input").css({"color": "green", "font-weight": "bold"})'))
    }
  })
}

shinyApp(ui, server)

Keep in mind that this approach only changes the css when an item is selected. If you prefer to have the colors displayed at all times, a different solution may be needed. Let me know if this solution meets your requirements!

Answer №2

If we combine @kluu's and my previous answers, I believe we can achieve the desired outcome. However, it's worth noting that the order of the items determines the color in the dropdown mode, not their data-value.

library(shiny)
library(shinydashboard)
library(shinyjs)

ui <- fluidPage(
  shinyjs::useShinyjs(),
  inlineCSS(".selectize-dropdown-content > .option:nth-child(1) {
            font-weight:bold;
            color:red;
            }
            .selectize-dropdown-content > .option:nth-child(2) {
            font-weight:bold;
            color:blue;
            }
            .selectize-dropdown-content > .option:nth-child(3) {
            font-weight:bold;
            color:green;
            }

            "
  ),
  tabItem(tabName = "comp",
          fluidRow(
            selectInput("mySelectMenu", "",c(1,2,3),selected = NULL, multiple = FALSE
            )))
)

server <- function(input, output, session) { 
  observeEvent(input$mySelectMenu,{
    currentIndividual<-as.numeric(input$mySelectMenu)
    # toggleFunction(currentIndividual)
  },ignoreInit=TRUE)

  observeEvent(input$mySelectMenu, {
    if (input$mySelectMenu == 1) {
      runjs(paste0('$(".selectize-input").css({"color": "red", "font-weight": "bold"})'))
    }
    if (input$mySelectMenu == 2) {
      runjs(paste0('$(".selectize-input").css({"color": "blue", "font-weight": "bold"})'))
    }
    if (input$mySelectMenu == 3) {
      runjs(paste0('$(".selectize-input").css({"color": "green", "font-weight": "bold"})'))
    }
  })
}

shinyApp(ui, server)

Answer №3

When determining the color based on the order of appearance in the list rather than the value it holds, you have the option to utilize nth-child:

.selectize-dropdown-content > .option:nth-child(2) {
  font-weight:bold;
  color:red;
}

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

JavaScript Loading Screen - Issues with window.onload functionality

I am currently working on creating a loading screen for my project. I need to use JavaScript to remove the CSS property "Display: none" from the page, but for some reason, my code is not functioning as expected. The Issue: I discovered that using window. ...

Issues observed with the functionality of the fixed position menu bar

Is it strange that the menu bar remains fixed at the top of the page while scrolling down, but ends up going under another div making it impossible to click on the menu? #cssmenu { position: fixed; left: 0; top: 0; height: 40px; width: 100%; ...

The default appearance of bootstrap-select appears to be flawed

Utilizing the amazing Bootstrap-select jQuery plugin has brought two unexpected default styles to my selectboxes. Despite inserting the necessary CSS and JS files into my website, all select boxes are displaying with these peculiar default settings (withou ...

Can you provide instructions on how to insert a hyperlink onto a background image?

Is it possible to add a hyperlink to this background image without causing it to disappear? Would creating a new class in the stylesheet be the way to go? (I encountered an issue where the image disappeared when trying to call the new class). body{ back ...

Border for status input like on Facebook

I tried to investigate with Firebug, but struggled to find a solution. How does Facebook wrap the border around the autosize input in the status section? I am particularly curious about the small triangle attached to the border. While using Firebug, I loca ...

What is the best way to change the background color for my photo gallery?

I'm currently working on a project to create a unique photo gallery where each image has a different colored background. I have six images in total, but right now all of them have a pink background. I've attempted adding another .popup class in t ...

What is the best way to apply a CSS class to my anchor tag using JavaScript?

I have a good grasp of using JavaScript to insert an anchor element into my webpage. For instance, var userName_a = document.createElement('a'); However, I am interested in adding a style name to that same element as well. I attempted the follo ...

Is it possible to dynamically change the color of a box shadow using an event handler?

I'm currently in the process of developing an application that consists of six distinct topics organized within a flexbox structure, complete with a box-shadow effect. My objective is to dynamically alter the color of the box-shadow through an event ...

The tooltip for the Google+ button stopped working

After setting up my Portfolio, I added a Google+ button. However, the page lacks styling and there seems to be an issue with the tooltip causing delays. Can anyone help me identify where the problem lies? ...

retrieve the data-task-IDs from the rows within the table

I am currently working with a table that looks like this: <table id="tblTasks"> <thead> <tr> <th>Name</th> <th>Due</th> ...

When displaying content within an iframe, toggle the visibility of div elements

I'm attempting to toggle the visibility of certain page elements based on whether the page is loaded in an iframe. <script>this.top.location !== this.location && (this.top.location = this.location);</script> The above code succes ...

center a horizontal line using StyledSheets in your project

After drawing a horizontal line, I noticed that it is positioned towards the left side of the screen. I am hesitant to increase its width. Are there any other methods to move it to the center? I attempted wrapping it with another view and using alignConten ...

Parallel calculation in R using an MPI cluster setup on WestGrid's High Performance Computing system (pbs file)

Currently, I am working with a significantly large dataset and looking to expedite the process using parallel calculation. In this endeavor, I have turned to WestGrid, a Canadian computing system equipped with interconnect clusters. To execute parallel ta ...

Sass Alert: The mixin called roboto-family is missing from the stylesheet. Trace: Problem detected in src/pages/forms/forms.scss at

Greetings, I am diving into the world of Ionic for the first time. Recently, I embarked on a new project in Ionic and decided to integrate a theme. To do so, I copied an .html file, an .scss file, and also created a .ts file. Forms.html <!DOCTYPE html ...

Tips for aligning a SPAN in a navbar to the center

When attempting to center the middle span, the right span containing buttons shifts downward. I am trying to create a navigation bar with one link on the left, three links in the center, and two buttons on the right. While floating the elements on the left ...

Deactivating the dark/light skin toggle in bs4Dash

Is it possible to change the main background color and header (navbar) background color in dark mode? I came across this link which suggests it may not be: Not able to change bs4Dash "dark" skin theme background in Shiny. Although we can easily ...

Internet Explorer 11 fails to interpret the attribute attr.xlink:href

I am a beginner in Angular 2 and I'm working on creating an icon component. The code I have below works perfectly in Chrome and Firefox, but unfortunately, it's not functioning in Internet Explorer 11. Here is what my component looks like: @Com ...

Restricting the quantity of categories displayed on facets within a facet chart

Here's how I created a facet_grid plot: data <- read.csv('sample.csv') ggplot(data, aes(category, count)) + geom_bar() + facet_grid(. ~ parent_id) The structure of my data is as follows: id,parent_id, category, count 1, 21, ...

Creating a visual that when clicked, reveals an enlarged version at a different location

Is there a way to make an image appear in a different location on the page when it's hovered over? I've searched online but couldn't find a solution using just HTML and CSS. Does anyone know how to achieve this effect? Image not hovered: ht ...

Mastering the alignment of tab content on Bootstrap 5 to ensure it always displays on the right side

With Bootstrap 5, I've managed to implement tab content that remains visible regardless of the active tab: <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="23414c4c5750575142536 ...