Search code examples
shinyshiny-server

Adding css to an element after clicking on actionButton


i'm trying to customize a login page with shiny. I have include a textInput like this textInput("login_username", "Username") and what i want to do is when the Username is not on the database then output$login_username 's borders will turn red. So how can I add CSS to an element after an event.

Let's say this is my if sentence :

if(is_validate){ /* action to do */ }
else { output$login_username <- /* action that i'm looking for */ }

Solution

  • Heres small example how to add the colors with the help of shinyjs package, I've also added a notification on bottom right with a message:

    library(shiny)
    library(shinyjs)
    
    allowedusers <- c("Pork_Chop","BKenz")
    jsCode <- "shinyjs.TextCol = function(params){$('#login_username').css('background', params);}"
    
    # For border color use below
    jsCode <- "shinyjs.TextCol = function(params){$('#login_username').css('border-color', params);}"
    
    ui <- fluidPage(
      useShinyjs(),
      extendShinyjs(text = jsCode),
      textInput("login_username", "Username"),
      actionButton("Login","Login")
    )
    
    server <- function(input, output,session) {
    
      observeEvent(input$Login,{
        req(input$login_username!="")
    
        if(!(input$login_username %in% allowedusers)){
          js$TextCol("red")
          showNotification("user doesnt exists",type="warning")
        }
        else{
          js$TextCol("white")
        }
      })
    }
    
    shinyApp(ui = ui, server = server)
    

    enter image description here

    enter image description here