0

I want to change the css class of a bootstrap button depending on the value of a checkbox. If the value of the checkbox (input$x) is checked ie. euqals TRUE, i want to add a class and when the value is false i want to remove the class. The Code below is what ive tried but it does not work. Does someone has a clue why it does not work?

library(shiny)
library(tidyverse)
library(htmltools)

ui = fluidPage(
  
  tags$style(
    HTML(
      ".testclass {background-color: pink;")),
  
  tags$div(style = "margin: 100px;",

  tags$input(type = "checkbox", "Check", id = "x"),    
      
  tags$button("Click", class="btn btn-default dropdown-toggle", id = "dropdownMenu1"))

  )

server = function(input, output, session){
  
  ### CUSTOM FUNCTIONS
  
  observeEvent(input$x, {
    if(isTRUE(input$x)){
      tagQuery(ui)$find("button")$filter(function(x, i) tagGetAttribute(x, "id") == "dropdownMenu1")$addClass("testclass")
    }else{
      tagQuery(ui)$find("button")$filter(function(x, i) tagGetAttribute(x, "id") == "dropdownMenu1")$removeClass("testclass")
    }
  })
}
shinyApp(ui, server)
werN
  • 109
  • 7

1 Answers1

2

tagQuery does not perform an action on the DOM, it just rewrites a tag. You can do:

library(shiny)
library(htmltools)

ui = fluidPage(
  
  tags$style(
    HTML(".testclass {background-color: pink;")
  ),
  
  tags$div(
    style = "margin: 100px;",
    
    tags$input(type = "checkbox", "Check", id = "x"),    
    
    uiOutput("mybutton")
  )
  
)

server = function(input, output, session){
  
  output[["mybutton"]] <- renderUI({
    btn <- tags$button("Click", class="btn btn-default dropdown-toggle", id = "dropdownMenu1")
    if(isTRUE(input$x)){
      btn <- tagQuery(btn)$addClass("testclass")
    }else{
      btn <- tagQuery(btn)$removeClass("testclass")
    }
    btn$selectedTags()
  })
  
}

shinyApp(ui, server)
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
  • 1
    looks good, thank you. are there basically any possibilities to manipulate the DOM from the server-side of a Shinyapp? Or is `renderUI()` the only one or the most common respectively and do I relay on Javascript otherwise? – werN Oct 27 '21 at 16:59