How can I keep an accordion collapse or open inside a nav-tab after page refresh using Bootstrap 4 and Jquery?
I'm trying to mix Bootstrap 4 Nav-tab and Accordion. My nav-tab is working properly after page refresh it stays on the active tab and I want to do the same with the accordion. I want the
keep the active accordion open or collapse when the page was refresh.
- <ul class = "nav nav-tabs">
- <li class = "nav-item"><a href = "#monitor" data-toggle = "tab" class = "nav-link active">Book Monitoring</a></li>
- <li class = "nav-item"><a href = "#history" data-toggle = "tab"class = "nav-link">Book's History</a></li>
- </ul>
- <!-- STARTS OF NAV-TAB -->
- <div class = "tab-content">
- <div class = "tab-pane container active" id = "monitor">
- <br />
- <h5>Monitoring of Books </h5>
- </div>
-
- <div class = "tab-pane container" id = "history">
- <br />
- <h5>History of Borrowed Books</h5>
-
- <!-- STARTS OF ACCORDION -->
- <div id = "accordion">
- <div class = "card">
- <div class = "card-header">
- <a href = "#stud_collapse" class = "card-link" data-toggle = "collapse">Borrowed by Students</a>
- </div>
- <div class = "collapse" id = "stud_collapse" data-parent = "#accordion">
- <div class = "class-body">
- Student's Data (Form and Tables Here)
- </div>
- </div>
- </div>
-
- <div class = "card">
- <div class = "card-header">
- <a href = "#teach_collapse" class = "card-link" data-toggle = "collapse">Borrowed by Teachers</a>
- </div>
- <div class = "collapse" id = "teach_collapse" data-parent = "#accordion">
- <div class = "class-body">
- Teacher's Data (Form and Tables Here)
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- <script>
- $(function() {
- //This is working properly for the Bootstrap Nav-Tab
- $('a[data-toggle="tab"]').click(function (e) {
- e.preventDefault();
- $(this).tab('show');
- });
- $('a[data-toggle="tab"]').on("shown.bs.tab", function (e) {
- var id = $(e.target).attr("href");
- localStorage.setItem('selectedTab', id)
- });
- var selectedTab = localStorage.getItem('selectedTab');
- if (selectedTab != null) {
- $('a[data-toggle="tab"][href="' + selectedTab + '"]').tab('show');
- }
-
- //This is what Ive tried but NOT working for the Bootstrap Accordion (collapsible), I tried to edit the code above for the accordion but no luck:
- $('a[data-toggle="collapse"]').click(function (e) {
- e.preventDefault();
- $(this).collapse('show');
- });
- $('a[data-toggle="collapse"]').on("shown.bs.collapse", function (e) {
- var id = $(e.target).attr("href");
- localStorage.setItem('selectedAccordion', id)
- });
- var selectedAccordion = localStorage.getItem('selectedAccordion');
- if (selectedAccordion != null) {
- $('a[data-toggle="collapse"][href="' + selectedAccordion + '"]').collapse('show');
- }
- });
- </script>