title: r - How do I automatically scroll to the bottom of a div in shinyapp?
body: <p>I wanted to keep the scroll bar at the bottom whenever new contents were added.</p>
  
  <pre><code>printText &lt;- function() {
    for(i in 1:20){
      Sys.sleep(0.1)
      shinyjs::html("text", paste("My text", i, "&lt;br&gt;"), add = TRUE)
      y = i + 1
    }
    return(y)
  }
  library(shiny)
  library(shinyjs)
  runApp(list(
    ui = shinyUI(fluidPage(
      shinyjs::useShinyjs(),
      titlePanel("Print consol output"),
      sidebarLayout(
        sidebarPanel(actionButton("go", "Go")),
        mainPanel(
          style = "overflow-y:scroll; max-height: 100px; position:relative;",
          div(id = "text")
        )
      )
    )),
    server = shinyServer(function(input, output, session){
      observeEvent(input$go, {
        shinyjs::html("text", "")
        y &lt;- printText()
      })
    })
  ))
  </code></pre>
  
  <p>I've found relevant solutions that called javascript but it didn't work in my case. </p>
  
  <p>Here's the js code:</p>
  
  <pre><code>function scrollToBottom(){
    var elem = document.getElementById('text');
    elem.scrollTop = elem.scrollHeight;
  };
  </code></pre>
  
  <p>I've tried to add includeScript before div to call the function, for example, includeScript("myJSfile.js"), but it didn't work.</p>
  
  <p>What was I doing wrong?</p>
  
  <p>Many thanks in advance.</p>