How could I automatically scroll to the bottom?

510 views
Skip to first unread message

Eric Hung

unread,
Apr 17, 2016, 12:27:10 AM4/17/16
to Shiny - Web Framework for R
I had this:
printText <- function() {
 
for(i in 1:20){
   
Sys.sleep(0.1)
    shinyjs
::html("text", paste("My text", i, "<br>"), 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
<- printText()
   
})
 
})
))

Now I wanted to keep the scroll bar at the bottom whenever new contents were added.

I found people might use javascript such as:
function scrollToBottom(){
 
var elem = document.getElementById('text');
  elem
.scrollTop = elem.scrollHeight;
};

I've tried to add includeScript before div to call the function, for example, includeScript("myJSfile.js"), but it didn't work.

What am I doing wrong?

Eric Hung

unread,
Apr 17, 2016, 2:05:07 PM4/17/16
to Shiny - Web Framework for R
I just figured out where the problems are. First, I actually contained "two" scrollToBottom functions in my real code. So I've renamed it as scrollToBottom2. Second, it seemed that style should be contained in div, so here's the code:

printText <- function() {
 
for(i in 1:20){
   
Sys.sleep(0.1)
    shinyjs
::html("text", paste("My text", i, "<br>"), 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
(

        includeScript
("~/myJSfile.js"),
        div
(

        style
= "overflow-y:scroll; max-height: 100px; position:relative;",
Reply all
Reply to author
Forward
0 new messages