www
www

Reputation: 39174

How to select the text in verbatimTextOutput by default in Shiny?

This is a related question to my previous question (Is it possible to have fixed width verbatimTextOutput and have texts change lines in Shiny?). I have the following shiny app (https://yuchenw.shinyapps.io/Shiny_verbatimtext_fixed/) with a verbatimTextOutput that can display long texts. Is it possible to select those texts by default? An example would be the behavior of the bookmark button. As the following screenshot shows, when the bookmark pop-up window shows up, the texts have been selected already. I would like to reproduce the same behavior using verbatimTextOutput.

enter image description here

Code

library(shiny)

ui <- function(request){
  fluidPage(
    tags$style(type='text/css', '#txt_out {white-space: pre-wrap;}'),
    column(
      width = 6,
      textInput(inputId = "txt", label = "Type in some texts",
                value = paste0(rep(letters, 10), collapse = "")),
      strong("Show the texts"),
      verbatimTextOutput("txt_out"),
      br(),
      bookmarkButton()
    )
  )
}
server <- function(input, output, session){
  output$txt_out <- renderText({
    input$txt
  })
}
enableBookmarking("url")
shinyApp(ui, server)

Upvotes: 2

Views: 1425

Answers (1)

www
www

Reputation: 39174

Thanks for @ismirsehregal's help. Here I shared a workaround of this question. This answer uses textAreaInput in read-only mode, not verbatimTextOutput as I originally asked for. However, I am satisfied with the outcome and final appearance of the textAreaInput.

I learned how to select texts based on this post (https://stackoverflow.com/a/50745110/7669809). I also learned how to set read-only mode for the textAreaInput from this post (Make textarea readonly with jquery). Here is my code.

library(shiny)

ui <- function(request){
  fluidPage(
    column(
      width = 6,
      tags$head(
        tags$script("
      Shiny.addCustomMessageHandler('selectText', function(message) {
        $('#txt_out').select();
        $('#txt_out').prop('readonly', true);
      });
    ")
      ),
      textInput(inputId = "txt", label = "Type in some texts",
                value = paste0(rep(letters, 10), collapse = "")),
      textAreaInput("txt_out", label = "Show the texts", heigh = "300px"),
      br(),
      bookmarkButton()
    )
  )
}
server <- function(input, output, session){
  observeEvent(input$txt, {
    updateTextAreaInput(session = session, inputId = "txt_out", value = input$txt)
  })
  observeEvent(input$txt_out, {
    session$sendCustomMessage("selectText", "select")
  })
}
enableBookmarking("url")
shinyApp(ui, server)

Here is how it looks when the app runs.

enter image description here

Upvotes: 2

Related Questions