Navigate to the top of the shiny dashboard panel using the sidebarmenu

Exploring the captivating shiny dashboard example illustrated below (adapted from ). One might ponder if there's a way to seamlessly scroll within one tab item, and upon transitioning to another tab item by selecting it in the sidebar, end up at the top of the new item instead of its previous position?

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(
    sidebarMenu(
      style = "position: fixed; overflow: visible;",
      menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")),
      menuItem("Widgets", tabName = "widgets", icon = icon("th"))
    )
  ),
  ## Body content
  dashboardBody(
    tabItems(
      # First tab content
      tabItem(tabName = "dashboard",
              fluidRow(
                box(plotOutput("plotA", height = 250)),
                
                box(
                  title = "Controls",
                  sliderInput("sliderA", "Number of observations:", 1, 100, 50)
                )
              ),
              fluidRow(
                box(plotOutput("plotB", height = 250)),
                
                box(
                  title = "Controls",
                  sliderInput("sliderB", "Number of observations:", 1, 100, 50)
                )
              ),
              fluidRow(
                box(plotOutput("plotC", height = 250)),
                
                box(
                  title = "Controls",
                  sliderInput("sliderC", "Number of observations:", 1, 100, 50)
                )
              ),
              
              fluidRow(
                box(plotOutput("plotD", height = 250)),
                
                box(
                  title = "Controls",
                  sliderInput("sliderD", "Number of observations:", 1, 100, 50)
                )
              ),
              
              fluidRow(
                box(plotOutput("plotE", height = 250)),
                
                box(
                  title = "Controls",
                  sliderInput("sliderE", "Number of observations:", 1, 100, 50)
                )
              ),
              
              fluidRow(
                box(plotOutput("plotF", height = 250)),
                
                box(
                  title = "Controls",
                  sliderInput("sliderF", "Number of observations:", 1, 100, 50)
                )
              )
              
      ),
      
      # Second tab content
      tabItem(tabName = "widgets",
              h2("Widgets tab content"),
              fluidRow(
                box(plotOutput("plot1", height = 250)),
                
                box(
                  title = "Controls",
                  sliderInput("slider1", "Number of observations:", 1, 100, 50)
                )
              ),
              fluidRow(
                box(plotOutput("plot2", height = 250)),
                
                box(
                  title = "Controls",
                  sliderInput("slider2", "Number of observations:", 1, 100, 50)
                )
              ),
              fluidRow(
                box(plotOutput("plot3", height = 250)),
                
                box(
                  title = "Controls",
                  sliderInput("slider3", "Number of observations:", 1, 100, 50)
                )
              ),
              fluidRow(
                box(plotOutput("plot4", height = 250)),
                
                box(
                  title = "Controls",
                  sliderInput("slider4", "Number of observations:", 1, 100, 50)
                )
              ),
              fluidRow(
                box(plotOutput("plot5", height = 250)),
                
                box(
                  title = "Controls",
                  sliderInput("slider5", "Number of observations:", 1, 100, 50)
                )
              ),
              fluidRow(
                box(plotOutput("plot6", height = 250)),
                
                box(
                  title = "Controls",
                  sliderInput("slider6", "Number of observations:", 1, 100, 50)
                )
              )
      )
    )
  )
)

server <- function(input, output) {
  set.seed(122)
  histdata <- rnorm(500)
  
  output$plot1 <- renderPlot({
    data <- histdata[seq_len(input$slider1)]
    hist(data)
  })
  
  output$plot2 <- renderPlot({
    data <- histdata[seq_len(input$slider2)]
    hist(data)
  })
  
  output$plot3 <- renderPlot({
    data <- histdata[seq_len(input$slider3)]
    hist(data)
  })
  
  output$plot4 <- renderPlot({
    data <- histdata[seq_len(input$slider4)]
    hist(data)
  })
  
  output$plot5 <- renderPlot({
    data <- histdata[seq_len(input$slider5)]
    hist(data)
  })
  
  output$plot6 <- renderPlot({
    data <- histdata[seq_len(input$slider6)]
    hist(data)
  })
  
  
  
  output$plotA <- renderPlot({
    data <- histdata[seq_len(input$sliderA)]
    hist(data)
  })
  
  output$plotB <- renderPlot({
    data <- histdata[seq_len(input$sliderB)]
    hist(data)
  })
  
  output$plotC <- renderPlot({
    data <- histdata[seq_len(input$sliderC)]
    hist(data)
  })
  
  output$plotD <- renderPlot({
    data <- histdata[seq_len(input$sliderD)]
    hist(data)
  })
  
  output$plotE <- renderPlot({
    data <- histdata[seq_len(input$sliderE)]
    hist(data)
  })
  
  output$plotF <- renderPlot({
    data <- histdata[seq_len(input$sliderF)]
    hist(data)
  })
}

shinyApp(ui, server)

Answer №1

Check out this approach that leverages the power of shinyjs. Every time a different item in the sidebar is selected, a JavaScript function is triggered. Take a look at the observeEvent code block I've integrated:

library(shiny)
library(shinyjs)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Simple Dashboard"),
  dashboardSidebar(
    sidebarMenu(id = "sidebarID", 
                style = "position: fixed; overflow: visible;",
                menuItem("Home", tabName = "home", icon = icon("home")),
                menuItem("Settings", tabName = "settings", icon = icon("cog"))
    )
  ),
  
  dashboardBody(
    useShinyjs(),
    extendShinyjs(text = 'shinyjs.scrolltop = function() {window.scrollTo(0, 0)};', functions = c("scrolltop")),
    
    tabItems(
      # First tab content
      tabItem(tabName = "home",
              fluidRow(
                box(plotOutput("plotX", height = 250)),
                
                box(
                  title = "Parameters",
                  sliderInput("sliderX", "Number of data points:", 1, 100, 50)
                )
              ),
              
              fluidRow(
                box(plotOutput("plotY", height = 250)),
                
                box(
                  title = "Parameters",
                  sliderInput("sliderY", "Number of data points:", 1, 100, 50)
                )
              )
      ),
      
      # Second tab content
      tabItem(tabName = "settings",
              h2("Settings Page"),
              
              fluidRow(
                box(plotOutput("plotZ", height = 250)),
                
                box(
                  title = "Configure Parameters",
                  sliderInput("sliderZ", "Number of data points:", 1, 100, 50)
                )
              )
      )
    )   
  )
)

server <- function(input, output) {
  
  observeEvent(input$sidebarID, {
    js$scrolltop()
  })
  
  set.seed(123)
  histdata <- rnorm(500)
  
  for (i in 1:6) {
    plot_name <- paste("plot", i, sep="")
    input_name <- paste("input$slider", i, sep="")
    
    output[[plot_name]] <- renderPlot({
      hist(histdata[seq_len(eval(parse(text=input_name)))])
    })
  }
}

shinyApp(ui, server)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Styled Components do not have the ability to define :hover states

export const WatchVideoButtonWrapper = styled.div` position: absolute; bottom: 80px; right: 33px; background-color: ${(props) => props.bgColor}; color: ${(props) => props.color}; border-radius: 100px; transition: all 0.1s; ...

What is the method for specifying the HTML file extension within Visual Studio?

I am having issues with my project recognizing the CSS and other files in the HTML files I have created, even though I have double-checked the extension paths. How can I resolve this problem? https://i.stack.imgur.com/85ooE.png https://i.stack.imgur.com/F ...

During the build process, Next.js encounters difficulty loading dynamic pages

My Next.js application is utilizing dynamic routes. While the dynamic routes function properly in development mode, I encounter a 404 error when deploying the built app to Netlify. https://i.stack.imgur.com/45NS3.png Here is my current code setup: In _ ...

What steps should be taken to safely sanitize untrusted JSON data before parsing it with JSON.parse method

How can we properly sanitize a user-provided JSON string to prevent any vulnerabilities before executing JSON.parse(untrustedString)? My main concern revolves around prototype pollution, but I'm also interested in knowing about any other potential ri ...

Inquiry about how TypeScript handles object property references when passed into functions

As a newcomer to TypeScript, I am exploring the creation of a range slider with dual handles using D3.js. I have developed a simple class for managing the slider objects: export class VerticalRangeSlider{ private sliderContainer: d3.Selection<SVGG ...

The proper method for transforming the "lookup" function into a vectorized format

I am in search of a swift and effective approach to solve the issue detailed below. Any assistance would be highly valued, thank you in advance! I possess several large csv files containing varied information about the same entity, but for my final comput ...

Adjust alterations in a Vue Component to apply to separate routes

I have a Filter tab component that I use in various routes. When I click on a tab, it becomes active. After clicking on one tab, I want it to remain active in other routes as well. How can I achieve this? Any suggestions or articles would be greatly apprec ...

What is the correct way to utilize ng-if/ng-show/ng-hide to hide or show HTML elements within the app.run function

I am currently working on developing an app that loads views correctly. HTML: <body> <loading outerWidth='1000' outerHeight='1000' display='isReady'></loading> <div class='wrapper' ng-sho ...

The complete rendering of angular-google-maps is only achieved after resizing the browser

<ui-gmap-google-map center="{latitude: 43.100187, longitude: -77.6329959}" zoom='8'> </ui-gmap-google-map> https://i.sstatic.net/9F2eb.jpg All necessary files were loaded via bower and the dependency was added t ...

When emitting events in Vue.js, they do not automatically bubble up to higher level parent or grandparent elements

I'm trying to dispatch a custom event that will bubble up from the grandchild element through the child element to the parent element, but for some reason it's not working. Even manually triggering the event on either the parent or child element ...

Concealing choices that have already been chosen in a ReactJS select dropdown menu

My challenge involves having 3 select boxes with the same option values, where users set security questions. Each question is selected and answered by the user. I fetched security questions via an API call and stored them in an array named "securityQuestio ...

Using PHP to convert JSON data into the Google Chart API

I am facing an issue with parsing my PHP generated JSON array into a Google chart. I have integrated JQuery, but for some reason, I am struggling to parse the JSON data. I execute a MySQL query to fetch data from the database. Then, I encode the query resu ...

Retrieving fresh CSS data from earlier animated elements within a Greensock timeline

In my code, I am using a TimelineLite() to perform a series of sequential tweens with .to(). What I want to achieve is accessing the output value from one of the early tweens in order to use it for constructing later tweens. Is there any way to retrieve t ...

Instead of displaying a regular text box, the output unexpectedly shows "Printing [object HTML

There are some HTML and JavaScript files that I have. I've written some functions in my JavaScript file to save the values of different input fields. However, when I try to print the description, it just displays [object HTMLInputElement]. This mak ...

Having trouble getting my JS/CSS code to work for a single image music play/pause button. Any suggestions on how to fix it?

I'm currently working on a project and trying to incorporate a music button into the navigation bar. The goal is for the song to play when clicked, and then pause when clicked again. However, I've encountered some issues with getting it to functi ...

What is the best way to retrieve the value of a cell in the parent gridview while navigating through the child gridview?

I am facing an issue with a JavaScript function that is used to expand and collapse a child gridview inside its parent gridview. My problem arises when I try to retrieve the value of a specific cell in the current row of the parent gridview, or even just i ...

Is it possible to create a new field in mongoDB from a separate collection without any dependencies?

I manage two different sets of data: profiles and contents The profiles collection is structured as follows: { _id: ObjectId('618ef65e5295ba3132c11111'), blacklist: [ObjectId('618ef65e5295ba3132c33333'), ObjectId('618ef65e5295 ...

What steps should I take to ensure my .js.erb files are compatible with Rails 7?

I have been following a Rails Tutorial on Building a Link Shortener with Rails 6 and Ruby 2.xx to create an app. However, I am using Rails 7.0.4 and Ruby 3.0.0. I encountered an issue with my create.js.erb file not functioning properly. After some research ...

Tips for dynamically loading fresh Google Adsense code with JavaScript without any user interaction

Recently, Google made a change in their ad code by replacing <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js</script> with <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygo ...

Unable to get Express router post function to properly function

Issue: var express = require('express'); var router = express.Router(); Route.js: Setting up Post route router.route('/signup') .post(function (req, res) { console.log('post signup called', req.body); re ...