WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

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">
<head>
<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>
<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>

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:

Advertisements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties