Retaining the Chosen Tab upon Page Reload in Bootstrap 5.1

Struggling to maintain the selected tab active after page refresh. It's worth noting that I'm using Bootstrap 5.1 and have tried various solutions found for different versions without success.

    <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
      <li class="nav-item" role="presentation">
        <button class="nav-link active" id="pills-home-tab" data-bs-toggle="pill" data-bs-target="#pills-home" type="button" role="tab" aria-controls="pills-home" aria-selected="true">Home</button>
      </li>
      <li class="nav-item" role="presentation">
        <button class="nav-link" id="pills-profile-tab" data-bs-toggle="pill" data-bs-target="#pills-profile" type="button" role="tab" aria-controls="pills-profile" aria-selected="false">Profile</button>
      </li>
      <li class="nav-item" role="presentation">
        <button class="nav-link" id="pills-contact-tab" data-bs-toggle="pill" data-bs-target="#pills-contact" type="button" role="tab" aria-controls="pills-contact" aria-selected="false">Contact</button>
      </li>
    </ul>
    <div class="tab-content" id="pills-tabContent">
      <div class="tab-pane fade show active" id="pills-home" role="tabpanel" aria-labelledby="pills-home-tab">...</div>
      <div class="tab-pane fade" id="pills-profile" role="tabpanel" aria-labelledby="pills-profile-tab">...</div>
      <div class="tab-pane fade" id="pills-contact" role="tabpanel" aria-labelledby="pills-contact-tab">...</div>
    </div>

If you need guidance on tabs in Bootstrap 5.1, refer to: https://getbootstrap.com/docs/5.1/components/navs-tabs/#methods

I don't have experience with JavaScript yet, but I would really appreciate your help with this issue.

Answer №1

For a solution using JavaScript, try out this example code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Maintain Bootstrap Tab Selection on Page Reload</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/jquery-3.5.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
    $('a[data-toggle="tab"]').on('show.bs.tab', function(e) {
        localStorage.setItem('activeTab', $(e.target).attr('href'));
    });
    var activeTab = localStorage.getItem('activeTab');
    if(activeTab){
        $('#myTab a[href="' + activeTab + '"]').tab('show');
    }
});
</script>
</head>
<body>
    <div class="m-3">
        <ul class="nav nav-tabs" id="myTab">
            <li class="nav-item">
                <a href="#sectionA" class="nav-link active" data-toggle="tab">Section A</a>
            </li>
            <li class="nav-item">
                <a href="#sectionB" class="nav-link" data-toggle="tab">Section B</a>
            </li>
            <li class="nav-item">
                <a href="#sectionC" class="nav-link" data-toggle="tab">Section C</a>
            </li>
        </ul>
        <div class="tab-content">
            <div id="sectionA" class="tab-pane fade show active">
                <h3>Section A</h3>
                <p>Aliquip placeat salvia cillum iphone...</p>
            </div>
            <div id="sectionB" class="tab-pane fade">
                <h3>Section B</h3>
                <p>Vestibulum nec erat eu nulla rhoncus fringilla...</p>
            </div>
            <div id="sectionC" class="tab-pane fade">
                <h3>Section C</h3>
                <p>Nullam hendrerit justo non leo aliquet...</p>
            </div>
        </div>
    </div>    
</body>
</html>

Answer №2

Here's an example of how to utilize BS-5.1 nav pills while saving the active pill ID to Window.localStorage:

By the way, in the Code Snippet, localStorage doesn't function correctly. Therefore, I've prepared an example on CodePen:

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cba9a4a4bfb8bfb9aabb8bfee5fae5f8">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a1815150e090e081b0a3a4f544b5449">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

<ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
  <li class="nav-item" role="presentation">
    <button class="nav-link active" id="pills-home-tab" data-bs-toggle="pill" data-bs-target="#pills-home" type="button" role="tab" aria-controls="pills-home" aria-selected="true">Home</button>
  </li>
  <li class="nav-item" role="presentation">
    <button class="nav-link" id="pills-profile-tab" data-bs-toggle="pill" data-bs-target="#pills-profile" type="button" role="tab" aria-controls="pills-profile" aria-selected="false">Profile</button>
  </li>
  <li class="nav-item" role="presentation">
    <button class="nav-link" id="pills-contact-tab" data-bs-toggle="pill" data-bs-target="#pills-contact" type="button" role="tab" aria-controls="pills-contact" aria-selected="false">Contact</button>
  </li>
</ul>
<div class="tab-content" id="pills-tabContent">
  <div class="tab-pane fade show active" id="pills-home" role="tabpanel" aria-labelledby="pills-home-tab">...</div>
  <div class="tab-pane fade" id="pills-profile" role="tabpanel" aria-labelledby="pills-profile-tab">...</div>
  <div class="tab-pane fade" id="pills-contact" role="tabpanel" aria-labelledby="pills-contact-tab">...</div>
</div>
const pillsTab = document.querySelector('#pills-tab');
const pills = pillsTab.querySelectorAll('button[data-bs-toggle="pill"]');

pills.forEach(pill => {
  pill.addEventListener('shown.bs.tab', (event) => {
    const { target } = event;
    const { id: targetId } = target;
    
    savePillId(targetId);
  });
});

const savePillId = (selector) => {
  localStorage.setItem('activePillId', selector);
};

const getPillId = () => {
  const activePillId = localStorage.getItem('activePillId');
  
  // if local storage item is null, show default tab
  if (!activePillId) return;
  
  // call 'show' function
  const someTabTriggerEl = document.querySelector(`#${activePillId}`)
  const tab = new bootstrap.Tab(someTabTriggerEl);

  tab.show();
};

// get pill id on load
getPillId();

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

ScriptManager is not accessible in the current ASP.Net Core Razor Page context

I'm facing an issue where I have a view (such as Index.cshtml) and a page model (like Index.cshtml.cs). In the view, there's a JavaScript function that I want to call from the OnPost() method in the page model. I tried using ScriptManager for thi ...

Show a single item from the database sequentially and cycle through the rest in a timed loop

I am working on a project that requires displaying specific details on the main screen of my office. The challenge I'm facing is that I need to show only one item at a time and then cycle through each item within a specified time period. Below are th ...

Arrangement of Bootstrap card components

Each card contains dynamic content fetched from the backend. <div *ngFor="let cardData of dataArray"> <div class="card-header"> <div [innerHtml]="cardData.headerContent"></div> </div> <d ...

How to associate an object with a component in Angular2/TypeScript using HTTP

I am currently working on displaying a list of item names retrieved from a REST API. By utilizing the map function on the response observable and subscribing to it, I was able to obtain the parsed items object. Now, my challenge is how to bind this object ...

The behavior of Material-UI Drawer varies when used on tablets

Encountering some strange issues with the Material-UI drawer component. It's scrolling horizontally on my iPad, while it scrolls vertically on my MacBook and Android Phone. Expected Result on MacBook: https://i.sstatic.net/txBDf.png On my MacBook, it ...

Combining input groups (including addons) with helpful text in Bootstrap 4

I'm having trouble getting Help-texts to appear properly (specifically at the bottom of the field) when using Bootstrap 4's input-groups with add-ons. This is the code I have so far: <div class="input-group mb-3"> <div class="input- ...

What is the best way to exchange configuration data among Javascript, Python, and CSS within my Django application?

How can I efficiently configure Javascript, Django templates, Python code, and CSS that all rely on the same data? For example, let's say I have a browser-side entry widget written in Javascript that interacts with an embedded Java app. Once the user ...

"Encountering a problem with the Flicker API while trying to view personal

I've been attempting to retrieve my personal photos using the following function with a node package obtained from this source https://www.npmjs.com/package/flickrapi\ When trying to access pictures of another user like 136485307@N06 (Apollo Im ...

Guide to center-aligning ElementUI transfer components

Has anyone successfully incorporated ElementUI's transfer feature inside a card element and centered it? https://jsfiddle.net/ca1wmjLx/ Any suggestions on how to achieve this? HTML <script src="//unpkg.com/vue/dist/vue.js"></ ...

What is the most efficient method for adding each unique unordered list element with a specific class to the nearest parent article tag

The current code structure looks like this: <article id="post-529"></article> <ul class="post-meta"></ul> <article id="post-530"></article> <ul class="post-meta"></ul> <article id="post-531"></a ...

Can Ajax be utilized to invoke an internal function within a web application?

Brand new to PHP, this is a whole new world for me. Currently, I am attempting to dynamically update a drop down list from 1-10 based on the selection of a previous drop down list. The initial drop down list allows you to choose tables numbered 1-35, whil ...

Is it possible to integrate Wavify with React for a seamless user experience?

For my website designs, I have been experimenting with a JavaScript library known as Wavify (https://github.com/peacepostman/wavify) to incorporate wave animations. Recently delving into the world of React, I pondered whether I could integrate Wavify into ...

I am attempting to change a "+" symbol to a "-" symbol using a Bootstrap toggle feature

Click on the text to reveal more information that drops down below. I am using Bootstrap icons and attempting to show a "+" icon when the toggle is collapsed, and a "-" icon when it's open. I've been trying to use display properties, but haven&ap ...

What is the process for configuring simultaneous services on CircleCI for testing purposes?

My current project involves running tests with Jasmine and WebdriverIO, which I want to automate using CircleCI. As someone new to testing, I'm a bit unsure of the process. Here's what I've gathered so far: To run the tests, I use npm tes ...

Exploring the Terrain: Troubleshooting Meteor CSS with Twitter Bootstrap

Recently, I have encountered an issue that perplexes me - I am unable to debug less code in my meteor app when the twbs:boostrap package is present. Interestingly, everything works fine when I remove it, but as soon as I add it back, the CSS seems to be co ...

eliminate the firebase firestore query using onSnapshot

Seeking assistance with the following code snippet: firebase.firestore() .collection("chatrooms") .doc(`${chatId}`) .collection(`${chatId}`) .orderBy("timestamp") .limit(50).onSnapshot((snapshot) => { //performing oper ...

Passing data to server-side PHP script using AJAX technology

Currently, I'm facing an issue with passing variables to a PHP script using onclick. It seems that I am making a mistake somewhere. To demonstrate the problem, let's say I have the following code snippet in my main page: <img src="myImage.jp ...

How to Handle 404 Errors for Specific Express Routes and Not Others

Struggling with the setup of a single page app using Angular routes on the front end, while facing backend issues. All database-related routes are functional, but any additional route designed to serve an HTML file or simple text like "hello world" result ...

Error Encountered While Serializing Products in getServerSideProps in Next.js v14

I am using Next.js version 14.2.3 and I am currently trying to retrieve a list of products from Firestore by utilizing the getProducts function from @stripe/firestore-stripe-payments within getServerSideProps. However, I am facing a serialization error: ...

Steps for including a subdocument within a mongoose schema

I am currently working on setting up a subdocument within a mongoose schema using node.js/Express. There are two schemas in play: Member and Address Member.js // app/models/member.js // Loading mongoose to define the model var mongoose = require(' ...