3

This is a very common feature among other webapps, but in R Shiny, how do you add a button that brings the user back to the top of the page when clicked?

In addition to that, is it possible to set how far up or down the user's view moves to?

Many thanks, I searched for a while but can't find any posts about this.

reaker
  • 145
  • 1
  • 9

2 Answers2

5

use the "gotop" package

available on CRAN

install it by calling install.package("gotop")

very simple to use, just add use_gotop() anywhere in the UI and you're good.

Junde Liu
  • 51
  • 1
  • 1
4

Using the shinyjs package, you can define a simple jump to top function along the lines of

jscode <- "shinyjs.toTop = function() {document.body.scrollTop = 0;}"

And you can then assign the code to a button in the ui

  useShinyjs(),
  extendShinyjs(text = jscode),
  actionButton("toTop", "jump to top")

And the have an observer in the server that executes the javascript when the button is clicked, something like

observeEvent(input$toTop, {
    js$toTop();
 })

Note that I have not tested this answer, but it should be enough to point you in the right direction (for example, the javascript might not work with different browsers)

yeedle
  • 4,918
  • 1
  • 22
  • 22