Using Bootstrap Tabs with Local Storage to Remember User Preferences in the Browser

When building interactive web applications, it's often useful to remember user preferences even after they leave the page. One common scenario is remembering which tab a user last viewed in a tabbed interface. In this post, we’ll walk through how to use Bootstrap tabs combined with local storage to achieve this functionality.

Overview
Bootstrap is a popular front-end framework that provides easy-to-use components for creating responsive layouts and interactive elements. One of these components is the tabbed interface, which allows users to switch between different sections of content without leaving the page.

Local storage is a web storage feature that allows web applications to store data in the browser. This data persists even after the user navigates away from the page, making it ideal for saving user preferences.

The Setup
To demonstrate this, we'll create a simple webpage with two Bootstrap tabs. We'll use JavaScript and jQuery to store the user's selected tab in local storage and ensure the same tab is displayed when the user returns to the page.

HTML Structure
Here’s the basic HTML structure for our tabs:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tab Example</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<ul class="nav nav-tabs" id="myTabs">
<li class="nav-item">
<a class="nav-link active" id="tab1-link" data-bs-toggle="tab" href="#tab1">Tab 1</a>
</li>
<li class="nav-item">
<a class="nav-link" id="tab2-link" data-bs-toggle="tab" href="#tab2">Tab 2</a>
</li>
</ul>

<div class="tab-content">
<div class="tab-pane fade show active" id="tab1" style="overflow-x: auto;">
<h1 class="mt-2">Tab 1</h1>
</div>
<div class="tab-pane fade" id="tab2" style="overflow-x: auto;">
<h1 class="mt-2">Tab 2</h1>
</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
function storeSelectedTab(tabId) {
localStorage.setItem('selectedTab', tabId);
}

function retrieveSelectedTab() {
return localStorage.getItem('selectedTab');
}

$(document).ready(function () {
var storedTab = retrieveSelectedTab();
if (storedTab) {
$('#myTabs a[href="#' + storedTab + '"]').tab('show');
}

$('#myTabs a').on('shown.bs.tab', function (e) {
var selectedTabId = $(e.target).attr('href').substring(1); // Get the id of the selected tab
console.log("tab = " + selectedTabId);
storeSelectedTab(selectedTabId); // Store the selected tab
});
});
</script>
</body>
</html>



Additional keyword: jquery tab, bootstrap tab

Last update on Sep 14, 2024

Tags: tabpane, tab-pain, localstorage

Back to Posts

Comments

No comments yet.

ForceTeach Corporation 2024