'Internal link between tabs to specific section in R Shiny app
I want to link to a specific content of another tabPanel
within an R Shiny app. I've found plenty of advice on how to do the half part of it respectively: there are solutions how to use an anchor
tag to link to content within a tabPanel
...
... and on hwo to direct the link to another tabPanel
:
- SO: [Shiny]: Add link to another tabPanel in another tabPanel
- SO: Linking to a tab or panel of a shiny app
- SO: Externally link to specific tabPanel in Shiny App
- Creating Internal Links - Defining Application Navigation by David Ruvolo
However, I need a combination of both: a link switching the view to another tabPanel
at a specific location. In this app, based on mihasa's example, there are two tabPanels
, where the first (Home
) holds some text upon clicking that, the app should redirect to a section with the id visitme
in Tab2
.
library(shiny)
ui = shinyUI(
navbarPage("Header",
tabPanel("Home",
fluidPage(
"bring me to the desired point in Tab2")),
tabPanel("Tab2",
"Some Text inside Tab 2.",
div("This is a long div to visualize the redirection",
style = "background-color: gray;
height: 1000px;
width: 100px;"),
div(id = "visitme",
"This is the part where the redirection shall land."),
div("Another long div",
style = "background-color: gray;
height: 500px;
width: 100px;"))))
server = function(input, output, session){}
runApp(shinyApp(ui, server), launch.browser = TRUE)
Solution 1:[1]
Using K. Rohde's answer as starting point, their JavaScript was extended by a second argument for the given id and a command, that scrolls to it (document.getElementById(anchorName).scrollIntoView()
), allows to move to a certain section within a given tabPanel
after switching to it.
library(shiny)
ui = shinyUI(
navbarPage("Header",
tabPanel("Home",
tags$head(tags$script(HTML('
var fakeClick = function(tabName, anchorName) {
var dropdownList = document.getElementsByTagName("a");
for (var i = 0; i < dropdownList.length; i++) {
var link = dropdownList[i];
if(link.getAttribute("data-value") == tabName) {
link.click();
document.getElementById(anchorName).scrollIntoView({
behavior: "smooth"
});
};
}
};
'))),
fluidPage(
span("bring me to end of tab2",
onclick = "fakeClick('Tab2', 'visitme')"))),
tabPanel("Tab2",
"Some Text inside Tab 2.",
div("This is a long div to visualize the redirection",
style = "background-color: gray;
height: 1000px;
width: 100px;"),
div(id = "visitme",
"This is the part where the redirection shall land."),
div("Another long div",
style = "background-color: gray;
height: 1000px;
width: 100px;"))))
server = function(input, output, session){}
runApp(shinyApp(ui, server), launch.browser = TRUE)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | bathyscapher |