Lev
Lev

Reputation: 833

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.!

Upvotes: 0

Views: 26

Answers (2)

Lev
Lev

Reputation: 833

Already fixed:

Followin @Stéphane solution and changing getElementById('log'); to getElementById('preLog')

library(shiny)
library(shinyjs)

js <- "
$(document).on('shiny:value', function(evt){
  if(evt.name == 'log'){
    setTimeout(function(){
      var objDiv = document.getElementById('preLog');
      objDiv.scrollTop = objDiv.scrollHeight - objDiv.clientHeight;
    }, 0); 
  }
});
"

ui <- fluidPage(
  tags$head(
  tags$script(HTML(js))
  )
  ,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)

Upvotes: 0

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84519

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)

Upvotes: 1

Related Questions