'Django js tabs keep selected tab on page refresh
I'm working with js tabs in Django and they work fine but I'd like to keep the selected tab active on that moment on page refresh. I found this example but it doesn't work https://www.tutorialrepublic.com/faq/how-to-keep-the-current-tab-active-on-page-reload-in-bootstrap.php
This is the script I'm using:
{% extends "bioinfointerface/base.html" %}
{% load static %}
{% block content %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Keep Selected Bootstrap Tab Active on Page Refresh</title>
<script>
$(function(){
var hash = window.location.hash;
hash && $('ul.nav a[href="' + hash + '"]').tab('show');
$('.nav-tabs a').click(function (e) {
$(this).tab('show');
var scrollmem = $('body').scrollTop() || $('html').scrollTop();
window.location.hash = this.hash;
$('html,body').scrollTop(scrollmem);
});
});
$(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>Vestibulum nec erat eu nulla rhoncus fringilla...</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>
{% endblock %}
In base.html I load:
<!-- Bootstrap core JS-->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<!-- Core theme JS-->
<script src="{% static 'bioinfointerface/js/scripts.js' %}"></script>
<link rel="stylesheet" type="text/css" href="{% static 'bioinfointerface/css/bootstrap.min.css' %}" />
<script src="{% static 'bioinfointerface/js/jquery.js' %}"></script>
<script src="{% static 'bioinfointerface/js/bootstrap.min.js' %}"></script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
