I'm trying to create a box in rshiny, which will have the background color set by the input variable. I've created an output:
mainPanel(
tags$div(uiOutput("image", align = "right"), h2(textOutput("text")),
div(textOutput("text2"),div(style = "width: 5px;"), "w",div(style = "width: 5px;"), textOutput("text3"), style = "display: flex"),
div("tel. ", div(style = "width: 5px;"), textOutput("num"), style = "display: flex"),
div("e-mail: ", div(style = "width: 5px;"), textOutput("text4"), style = "display: flex"),
style= "width: 800px; height: 400px;color: black; font-size:15px;
border: 5px solid white; padding: 15px; margin: 20px", class = "test")
)
And now I'd like to modify the background color with a input by this:
eventReactive(input$kolor, {
if(input$kolor == 1)
{
HTML('<style type="text/css">
.test { background-color: white; }
</style>')
}
else if(input$kolor == 2)
{
HTML('<style type="text/css">
.test { background-color: green; }
</style>')
}
else if(input$kolor == 3)
{
HTML('<style type="text/css">
.test { background-color: blue; }
</style>')
}
})
Unforunately, when I change the input variable - nothing happens. Any tips how to do it?
We can use renderUI
to achive this:
library(shiny)
ui <- fluidPage(titlePanel("Hello Shiny!"),
sidebarLayout(sidebarPanel(
selectInput(
inputId = "color",
label = "Color",
choices = c("white", "green", "blue")
)
),
mainPanel(uiOutput("mydiv"))))
server <- function(input, output, session) {
output$mydiv <- renderUI({
div(
"background-color test",
width = "100px",
height = "100px",
style = sprintf("background-color:%s;", input$color)
)
})
}
shinyApp(ui, server)
Or we can use shinyjs::runjs
:
library(shiny)
library(shinyjs)
ui <- fluidPage(
useShinyjs(),
titlePanel("Hello Shiny!"),
sidebarLayout(
sidebarPanel(
selectInput(
inputId = "kolor",
label = "color",
choices = setNames(c("white", "green", "blue"), 1:3)
)
),
mainPanel(
tags$div(uiOutput("image", align = "right"), h2(textOutput("text")),
div(textOutput("text2"),div(style = "width: 5px;"), "w",div(style = "width: 5px;"), textOutput("text3"), style = "display: flex"),
div("tel. ", div(style = "width: 5px;"), textOutput("num"), style = "display: flex"),
div("e-mail: ", div(style = "width: 5px;"), textOutput("text4"), style = "display: flex"),
style= "width: 800px; height: 400px;color: black; font-size:15px;
border: 5px solid white; padding: 15px; margin: 20px", class = "test", id = "testid")
)
)
)
server <- function(input, output, session) {
observeEvent(input$kolor, {
runjs(sprintf("document.getElementById('testid').style.backgroundColor = '%s';", input$kolor))
})
}
shinyApp(ui, server)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.