How to keep the current tab active on page reload in Bootstrap

Topic: Bootstrap / SassPrev|Next

Answer: Use the HTML5 localStorage Object

In Bootstrap, if you refresh the page the tab is reset to default setting. However, you can use the HTML5 localStorage object to save some parameter for the current tab locally in the browser and get it back to make the last active tab selected on page reload.

Let's try out the following example to understand how it basically works:

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Keep Selected Bootstrap Tab Active on Page Refresh</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>
    $('a[data-toggle="tab"]').on('show.bs.tab', function(e) {
        localStorage.setItem('activeTab', $(e.target).attr('href'));
    var activeTab = localStorage.getItem('activeTab');
        $('#myTab a[href="' + activeTab + '"]').tab('show');
    <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 class="nav-item">
                <a href="#sectionB" class="nav-link" data-toggle="tab">Section B</a>
            <li class="nav-item">
                <a href="#sectionC" class="nav-link" data-toggle="tab">Section C</a>
        <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 id="sectionB" class="tab-pane fade">
                <h3>Section B</h3>
                <p>Vestibulum nec erat eu nulla rhoncus fringilla...</p>
            <div id="sectionC" class="tab-pane fade">
                <h3>Section C</h3>
                <p>Nullam hendrerit justo non leo aliquet...</p>

The jQuery code in the above example simply gets the <a> element's href attribute value when a new tab has been shown using the jQuery .attr() method and save it locally in the user's browser through HTML5 localStorage object. Later, when the user refresh the page it retrieves this data and activate the related tab via Bootstrap's .tab('show') method.

Related FAQ

Here are some more FAQ related to this topic:

Bootstrap UI Design Templates

Your Feedback:

We would love to hear from you, please drop us a line.