daj
daj

Reputation: 7183

R shiny - enabling keyboard shortcuts?

Is there a way to expose keyboard presses like function keys F1-F10 to control shiny, e.g. switching tabs?

Upvotes: 4

Views: 2329

Answers (1)

DeanAttali
DeanAttali

Reputation: 26323

I was able to come up with a semi-working solution, but shiny does have some limitations so I opened a bug with shiny.

Here's the code:

library(shiny)

jscode <- "
$(function(){ 
  $(document).keyup(function(e) {
    if (e.which >= 49 && e.which <= 57) {
      Shiny.onInputChange('numpress', e.which - 48);
    }
  });
})
"

runApp(shinyApp(
  ui = fluidPage(
    tags$script(HTML(jscode)),
    "Type a number to switch to that tab",
    tabsetPanel(
      id = "navbar",
      tabPanel("tab1", "Tab 1"),
      tabPanel("tab2", "Tab 2"),
      tabPanel("tab3", "Tab 3"),
      tabPanel("tab4", "Tab 4")
    )
  ),
  server = function(input, output, session) {
    observe({
      if (is.null(input$numpress)) {
        return()
      }
      updateTabsetPanel(session, "navbar", sprintf("tab%s", input$numpress))
    })
  }
))

And here's the link to the shiny issue describing the problem: https://github.com/rstudio/shiny/issues/928

Upvotes: 6

Related Questions