Whenever a tab is refreshed, the page will automatically redirect to the first tab

When using the application below, if the user is not in Tab 2 or Tab 3 and clicks on refresh, the page automatically goes to Tab 1. Is there a way to prevent this behavior and keep the user in their current tab after refreshing? Any suggestions on how to achieve this would be greatly appreciated!

library(shiny)
ui <- fluidPage(
  tabsetPanel(
    id="inTabset",
    tabPanel("Tab 1",actionButton("switch_tab", "Go to the third tab")
    ),
    tabPanel("Tab 2", "there!"),
    tabPanel("Tab 3", "there!"))

)

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

  observeEvent(input$switch_tab, {
    updateTabsetPanel(session, "inTabset",selected = "Tab 3")
  })

}
shinyApp(ui = ui, server = server)

Answer №1

To maintain state in your Shiny app, you can utilize the built-in bookmark system provided by Shiny. However, if you prefer a more discreet approach, consider incorporating the Cookie.js JavaScript library.

Integrate the Cookie.js JavaScript library into your Shiny app using the following code snippet:

 tags$head(tags$script(src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.1/js.cookie.min.js")),
        tags$head(tags$script(src="app.js")),
        tabsetPanel(
            id="inTabset",
            tabPanel("Tab 1",actionButton("switch_tab", "Go to the third tab")),
            tabPanel("Tab 2", "there!"),
            tabPanel("Tab 3", "there!")),

Create an app.js file within the www-directory of your Shiny root directory with the provided content:

$(document).ready(function(){
   $("a[data-toggle='tab']").click(function(){
     const tabId = $(this).data("value");
     Cookies.set('tabId', tabId);
   })
   const cookieTabId = Cookies.get("tabId");
   if(cookieTabId){
     console.log(`Restoring tab '${cookieTabId}'`); 
     $(`a[data-value='${cookieTabId}']`).tab('show');
   }
 })

The key components in the above JavaScript implementation are the jQuery selectors and the utilization of the show() method as defined in Bootstrap documentation.

If desired, you can also transmit the selected tab value to the server and persist session values for users in a data store, enabling state persistence across different browser sessions.

Download the solution from here.

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

What is the process for implementing an image as the background instead of a color for each column in a Google chart?

I'm currently working with Google Chart and I have set up a column chart. However, I am looking to display a background image instead of a background color in each column. Is this achievable with Google Chart? If so, how can I accomplish this? If anyo ...

How can I eliminate unnecessary gaps in a CSS slider design?

Currently, I am in the process of learning CSS3 and attempting to create a purely CSS slider. Everything has been going smoothly until I encountered an unexpected padding or margin within my slider. After making some adjustments to the margins, the issue ...

A guide to injecting HTML banner code with pure Vanilla Javascript

Looking for a solution to incorporate banner code dynamically into an existing block of HTML on a static page without altering the original code? <div class="wrapper"><img class="lazyload" src="/img/foo01.jpg"></div> <div class="wrapp ...

The selected Google Font Family remains unchanged

After taking a break, I decided to dive back into web development in order to create a simple webpage. My starting point is Bootstrap, and I am constructing my page based on that framework. However, I'm facing an issue with changing the font family of ...

A error was encountered stating that the formValidation function is not defined when the HTML form element is submitted

Having trouble calling a function and receiving an error message. How can I resolve this issue? The error message reads: index.html?email=&gebruikersnaam=&wachtwoord=&submit=Submit:1 Uncaught ReferenceError: formValidation is not defined at HT ...

What is the best way to switch between components when clicking on them? (The component displayed should update to the most recently clicked one

I am facing a challenge in rendering different components based on the navbar text that is clicked. Each onclick event should trigger the display of a specific component, replacing the current one. I have 5 elements with onclick events and would like to re ...

mobile-exclusive wordpress text area problem

There seems to be a padding issue that is only affecting mobile devices. https://i.stack.imgur.com/2Tbuc.png The cause of this problem has been somewhat identified, but the solution isn't clear without impacting the preview on computers. Here is th ...

Reduce the size of a container element without using jquery

In my Angular application, I have structured the header as follows: -- Header -- -- Sub header -- -- Search Box -- -- Create and Search Button -- -- Scroll Div -- HTML: <h1> Header </h1> <h3> Sub header </h3> <div class="s ...

Integrating CSS into dynamically generated table rows using jQuery

Having trouble applying CSS to table rows created via ajax request. Despite using jQuery to add CSS to newly generated rows, it only affects the existing table headers. The table already has a 'sortable' class which also doesn't apply to dy ...

Is it possible to initially design a login page using HTML/CSS and JavaScript, and then integrate VUE into it?

As part of a school project, I am tasked with developing a web-based application for a library system. The goal is to create a platform where librarians can login and manage books by adding, removing, or editing them. My responsibility lies in handling the ...

Finding the current HTML page URL in Ionic 2: A step-by-step guide

Can the URL of the current HTML page be obtained and then converted to PDF using the cordova-pdf-generator package? ...

Update the screen layout to a grid when the screen is resized

I have a very specific request regarding the user experience. I want to display four links within a container, positioned next to each other in one row with a vertical line separating them. For example: Link one | Link two | Link three | Link four This ...

What is the best way to split an array into smaller chunks?

My JavaScript program fetches this array via ajax every second, but the response time for each request is around 3 to 4 seconds. To address this delay, I attempted to split the array into chunks, however, encountered difficulties in completing the task: { ...

Remove dynamically created elements from an AngularJS div

Is there a way to remove an item from the criteria list when clicking the delete button? Currently, only the filter is being refreshed and not the tables. Any suggestions on how to resolve this issue? HTML <ul class="list-unstyled"> <l ...

JQuery, Draggable delete

I created a shopping cart with drag-and-drop functionality for nodes. http://jsfiddle.net/dkonline/Tw46Y/ Currently, once an item is dropped into the bucket (slot), it cannot be removed. I'm looking to add that feature where items can be removed from ...

Can you leverage the class declaration from a previous style in CSS when creating a new definition?

I have exhaustively searched for the solution without success, which is leading me to believe that it may not be achievable. With my limited understanding of CSS principles, I am inclined to think that this task could pose a challenge. However, before expl ...

Transform the snake code by incorporating a visual image as the face of the serpent

Can someone help me change the snake's face to an image instead of a color fill in this code? And how can I add arrows for mobile compatibility? (function() { // Insert JS code here })(); // Insert CSS code here This code snippet includes functi ...

Increase the worth of current value

Whenever a user enters their name into an input box, I want it to be shown after the word 'hello'. However, currently, the word 'hello' gets replaced by the user's name instead of being displayed after it. var name = document.ge ...

How can I utilize the LED flash on a Windows Phone using WinJS?

Currently delving into the world of WinJS and endeavoring to create an application that involves operating the LED Flash. I am seeking guidance on how to properly access the LED Flash functionality to allow for toggling it ON or OFF. Your insights on how ...

jQuery Mobile panel buttons are functioning properly within a maximum width of 300 pixels

I have constructed a panel that adjusts its size based on the device's screen using responsive design techniques. The code for this panel is as follows: <div data-role="panel" data-position="right" data-display="overlay" data-theme="a" id="add-for ...