I wanted to keep the scroll bar at the bottom whenever new contents were added.
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()
})
})
))
I've found relevant solutions that called javascript but it didn't work in my case.
Here's the js code:
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 was I doing wrong?
Many thanks in advance.
This works for me:
library(shiny)
ui <- fluidPage(
tags$head(
# Some css to style the div to make it more easily visible
tags$style(
'#outDiv{
height:150px;
overflow-y:scroll;
border: 1px solid black;
border-radius:15px;
padding:15px;
}
'
),
# Custom shiny to javascript binding
# scrolls "outDiv" to bottom once called
tags$script(
'
Shiny.addCustomMessageHandler("scrollCallback",
function(color) {
var objDiv = document.getElementById("outDiv");
objDiv.scrollTop = objDiv.scrollHeight;
}
);'
)
),
sidebarLayout(
sidebarPanel(
actionButton('go','Start Printing')
),
mainPanel(
div(id='outDiv',
htmlOutput('out')
)
# Text output
)
)
)
server <- function(input, output, session) {
autoInvalidate <- reactiveTimer(250, session) # Timer function
ptm <- proc.time() # Start time
startTxt <- '' # Start string to show on screen
# Function to print new line when reactiveTimer invalidates
startPrint <- function(){
output$out <- renderText({
ctm <- proc.time() - ptm
autoInvalidate() # Start invalidating function every n miliseconds
# Format string to print
curr.font <- sample(colours(distinct=T), 1)
curr.txt <- sprintf('<font color="%s"> %4.2f</font> seconds from start <br>', curr.font, ctm[[3]])
startTxt <<- paste(startTxt, curr.txt, collapse = '')
# Call custom javascript to scroll window
session$sendCustomMessage(type = "scrollCallback", 1)
return(startTxt)
})
}
observeEvent(input$go,{
startPrint()
})
}
runApp(shinyApp(ui,server))
The trick here is that I call the Javascript function to scroll the div every time I update the text output. Let me know if this answer is to convoluted.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.