rshinypre

Shiny automatically scrolldown PRE element


This is my MWE:

library(shiny)

ui <- fluidPage(
  uiOutput("log"),
  actionButton("test","Click")
)

server <- function(input, output,session) {
  
  RV<-reactiveValues(myText=as.character())
  
  observeEvent(input$test,{
    text<-as.character()
    for (i in 1:100) text<-paste0(text,"hello ",i,"\n")
    RV$myText<-text
  })
  
  output$log<-renderUI({
    sHtml<-paste0("<pre id=\"preLog\" style=\"width:100px;height:200px;overflow:auto\">",RV$myText,"</pre>")
    print(HTML(sHtml))
  })

}

shinyApp(ui = ui, server = server)

When I click on the button, the pre element is populated, but it shows the rows at the top. ¿How can I make it to automatically scroll to the bottom?

Thanks.!


Solution

  • Here is a way. I use verbatimTextOutput, which generates a pre element.

    library(shiny)
    
    js <- "
    $(document).on('shiny:value', function(evt){
      if(evt.name == 'log'){
        setTimeout(function(){
          var objDiv = document.getElementById('log');
          objDiv.scrollTop = objDiv.scrollHeight - objDiv.clientHeight;
        }, 0); 
      }
    });
    "
    
    ui <- fluidPage(
      tags$head(
        tags$script(HTML(js)),
        tags$style(HTML("#log {width:100px; height:200px; overflow:auto;}")), 
      ),
      br(),
      verbatimTextOutput("log"),
      actionButton("test", "Click")
    )
    
    server <- function(input, output, session) {
      
      RV <- reactiveValues(myText = as.character())
      
      observeEvent(input$test,{
        text <- as.character()
        for (i in 1:100) text <- paste0(text, "hello ", i, "\n")
        RV$myText <- text
      })
      
      output$log <- renderText({ RV$myText })
      
    }
    
    shinyApp(ui, server)