zhang jing
zhang jing

Reputation: 181

How to change the title color in shinydashboard from server using shinyjs

I want to change the title of header in shinydashboard, from the server part. Simple text, e.g. p(), can be changed, while it seems no changes in the title.

library(shinydashboard)
library(shiny)

header <- dashboardHeader(title='want to be red') |> 
        tagAppendAttributes(id='nn',.cssSelector = 'span')

side <- dashboardSidebar(
    useShinyjs(),
    inlineCSS(list('.red' = "color: red")),
    p(id = "p", "to red color")
)

body <- dashboardBody()

ui <- dashboardPage(header,side,body,title = 'nhanesR')

server <- function(input, output, session){
    toggleClass(id = 'nn', "red")
    toggleClass(id = 'p', "red")
}
shinyApp(ui,server)

Upvotes: 0

Views: 328

Answers (1)

lz100
lz100

Reputation: 7340

  1. You forget to library shinyjs
  2. Better to load shinyjs useShinyjs() in the body instead.
  3. For the title, you can't simply add the red class. The original stylesheet has a stronger selector that will prevent you to change color. We need to use an inline style, which has the almost highest priority to overwrite the color.
library(shinydashboard)
library(shiny)
library(shinyjs)
header <- dashboardHeader(title='want to be red') |> 
    tagAppendAttributes(id='nn',.cssSelector = 'span')

side <- dashboardSidebar(
    inlineCSS(list('.red' = "color: red")),
    p(id = "p", "to red color")
)

body <- dashboardBody(
    useShinyjs()
)

ui <- dashboardPage(header,side,body,title = 'nhanesR')

server <- function(input, output, session){
    runjs('$("#nn").css("color", "red")')
    toggleClass(id = 'p', "red")
}
shinyApp(ui,server)

Unless you want to change it dynamically, not sure why you want to use shinyjs to do this. We can do all of this with tags$style on the UI.

enter image description here

Upvotes: 2

Related Questions