0

I can add a link to an anchor in the ui with a("Go to Results", href = '#anchor_box') and have the user to click on it to go to this anchor.

But how to have the window 'sent to' #anchor_box programatically? For example when results are available at the end of an observeEvent() with a long running time?

tic-toc-choc
  • 815
  • 11
  • 26

1 Answers1

1

You could use javascript for that. There are several possibilities, one way would be to get the element and use scrollIntoView(), see anchor jumping by using javascript.

An easy way to use javascript in shiny, is library(shinyjs).

You could insert the following to tell R to move the element in focus:

runjs('
      document.getElementById("anchor_box").scrollIntoView();
    ')

In order to know, when to do so, you could wrap it within a observeEvent():

observeEvent(eventExpr = input$clck, handlerExpr = {...})

Downside would be that refreshing the page would not automatically "scroll up to the top".

Reproducible example:

library(shiny)
library(shinyjs)

ui <- fluidPage(

  a("Go to Results", href = '#anchor_box'),
  actionButton("clck", "Move Programmatically!"),

  plotOutput("plot", height = 1300),  
  div(id = "anchor_box", "HERE"),
  useShinyjs(),

)

server <- function(input, output, session) {

  output$plot <- renderPlot({
    plot(1)
  })

  observeEvent(eventExpr = input$clck, handlerExpr = {
    runjs('
      document.getElementById("anchor_box").scrollIntoView();
    ')
  })

}

shinyApp(ui, server)
ismirsehregal
  • 30,045
  • 5
  • 31
  • 78
Tonio Liebrand
  • 17,189
  • 4
  • 39
  • 59