skip to Main Content

I’m using CSS to style my applications. I’ve found that I need to repeatedly do more work with actionButtons because they come with default CSS classes whether I want them to or not. Take a look at this example:

library(shiny)

ui <- fluidPage(
  tags$head(
    tags$style(HTML("
                    .redbutton {
                    background-color: red;
                    }
                    "))
  ),
  actionButton("button1", "Hover", class = "redbutton")
)

server <- function(input, output, session) {
  
}

shinyApp(ui, server)

The button has the redbutton class applied, as I specified. However, the default CSS classes include on-hover and on-click behavior, changing the color of the button when hovered even though I do not desire this behavior.
Can this be avoided? I’d prefer not to add specific instances of ‘:hover’ into my css sheet for every class, just to disable the default behavior.

2

Answers


  1. One possibility is to do a function for a basic button:

    myButton <- function(id, label, class) {
      tags$button(id = id, class = paste0("action-button ", class), label)
    }
    

    But be aware that such a basic button has some CSS styles defined by the browser, and that’s rather ugly. So you should define a base class for your custom buttons.

    Login or Signup to reply.
  2. Another variant is to remove the unwanted CSS class, client-side, with javascript.
    Include this in your HTML head by adding it to your tags$head function:

    ## other server code ...
    tags$head(
    ## other header elements,
          tags$script("
            var dropClass = 'btn-default';
            $(document).ready(function() { 
                document.getElementsByClassName(dropClass)
                    .forEach(function(n){n.classList.remove(dropClass)});
            })
         ")
    )
    
    

    In this case, removing the ‘btn-default’ class should do the trick.

    Note that CSS also offers a pointer-events: none declaration to prevent triggering the hover style (but also other effects like cursor-shape).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search