Scroll automatically to the right side of a datatable

Viewed 53

Is there any way, in R Shiny, to set the scroll bar from a datatable automatically to the right side when rendered (i.e. to the last column), instead of the left side as it is set by default ?

Base example :

library(shiny)
runApp(shinyApp(
  ui = fluidPage(
    DT::dataTableOutput("results", width = 300)
  ),
  server = function(input, output, session) {
    output$results <- DT::renderDataTable(
      mtcars,
      options = list(scrollX = TRUE, bPaginate = F)
    )
  }
))
2 Answers

Add this line in the ui: tags$style('#results {direction: rtl;}')

library(shiny)
runApp(shinyApp(
    ui = fluidPage(
        DT::dataTableOutput("results", width = 300),
        tags$style('#results {direction: rtl;}')
    ),
    server = function(input, output, session) {
        output$results <- DT::renderDataTable(
            mtcars,
            options = list(scrollX = TRUE, bPaginate = F)
        )
    }
))
library(shiny)
runApp(shinyApp(
  ui = fluidPage(
    tags$div(id = "parent",
      DT::dataTableOutput("results", width = 300)
    ),
    tags$style("
               #parent {direction: rtl; max-height: 80vh; overflow: auto; margin: 0 auto} 
               #results {direction: ltr; float: left}")
  ),
  server = function(input, output, session) {
    output$results <- DT::renderDataTable(
      mtcars,
      options = list(scrollX = TRUE, bPaginate = F)
    )
  }
))

EDIT

Here is what you want:

library(shiny)
library(DT)

callback <- "
$('div.dataTables_scrollBody').animate({scrollLeft: '+=500'}, 1000);
"

runApp(shinyApp(
  ui = fluidPage(
    DTOutput("results", width = 300)
  ),
  server = function(input, output, session) {
    output$results <- renderDT(
      datatable(
        mtcars, 
        callback = JS(callback),
        options = list(scrollX = TRUE)
      )
    )
  }
))

1000 is 1000ms, this is the duration of the animation. I don't understand why +=300 is not enough.

Related