Search code examples
rshiny

Colour picker input not updating output in R Shiny


I am trying to test an idea of getting the colour the user selected and then using it for further tasks (for example, changing the colour of a ggplot object).

Before this, I'd like to extract the hex name from the colour picker. I have built a minimal app to test the idea, but it seems the input and output are not connected.

I am just wondering where the issue is?

library(shiny)

# UI definition
ui <- fluidPage(
    
    sidebarLayout(
        sidebarPanel(
            # Add the color input:
            tags$input(
                type  = "color", 
                id    = "exampleColorInput", 
                value = "#3ADA42", 
                title = "Choose your color", 
                class = "form-control form-control-color"
            )
        ),
        
        mainPanel(
            # Display the chosen colour
            textOutput("chosenColor")
        )
    )
)

# Server logic
server <- function(input, output) {
    
    # Observe the colour input and display the chosen value
    output$chosenColor <- renderText({
        paste("Chosen color:", input$exampleColorInput)
    })
}

# Run the application 
shinyApp(ui = ui, server = server)

Solution

  • You need to add some javascript to get the browser to send the new input values back to Shiny. Any shiny input from a package does this for you already. But when you make your own inputs from raw HTML, you've got to do it yourself. Add the following inside your fluidPage:

    tags$script(HTML("
            $(document).on('input', '#exampleColorInput', function() {
                var color = $(this).val();
                Shiny.setInputValue('exampleColorInput', color);
            });
        ")),