I am trying to optimize the accessibility of my shiny app for users that use screen readers. This involves making sure the app is navigable using the keyboard (mainly the tab key). I have run into a problem with the navlistPanel() ui element as the tabs are not keyboard-focusable. I think this may be due to the elements having a tabindex of -1. How can I override this behavior and make the navigation menu keyboard accessible?
MRE:
library(shiny)
ui <- fluidPage(
navlistPanel(
"Example Tabs",
tabPanel("Tab 1", "First content"),
tabPanel("Tab 2", "Second content"),
tabPanel("Tab 3", "Third content")
)
)
server <- function(input, output, session) {}
shinyApp(ui, server)
Usually I would have recommended using htmltools::tagQuery or tagAppendAttributes()
.
However, in this case tagQuery(tabPanel("Tab 2", "Second content"))
can only access the div
tags not the relevant a
tags because they are only generated when the server is up.
We can use JS directly instead to modify the tabindex attribute:
library(shiny)
library(htmltools)
ui <- fluidPage(
tags$script(HTML(
"
Shiny.initializedPromise.then(() => {
const links = document.getElementById('navlistID').getElementsByTagName('a');
for (const element of links) {
element.setAttribute('tabindex', 0);
}
});
"
)),
navlistPanel(
"Example Tabs",
id = "navlistID",
tabPanel("Tab 1", "First content"),
tabPanel("Tab 2", "Second content"),
tabPanel("Tab 3", "Third content")
)
)
server <- function(input, output, session) {}
shinyApp(ui, server)
Relevant docs: