How can I make the accordion and sub accordion stay open if a reload the page (clicking one of the items)? Do I have to write an own function to save the items that are open on open them on the page reload or is that a possibility with the built in javascript of bootstrap.
<div id="MainMenu">
<div class="list-group">
<a href="#menu0" class="list-group-item" data-toggle="collapse" data-parent="#MainMenu">Holz</a>
<div id="menu0" class="collapse">
<a href="/products/index/11" class="list-group-subitem">A</a>
<a href="/products/index/12" class="list-group-subitem">B</a>
<a href="/products/index/13" class="list-group-subitem">C</a>
<a href="/products/index/14" class="list-group-subitem">D</a>
<a href="#menu0_1" class="list-group-subitem" data-toggle="collapse" data-parent="#MainMenu">E</a>
<div id="menu0_1" class="collapse">
<a href="/products/index/15" class="list-group-subitem">E1</a>
<a href="/products/index/16" class="list-group-subitem">E2</a>
</div>
</div>
</div>
Just add data-toggle="collapse" and a data-target to element, to automatically assign control of a collapsible element. The data-target attribute accepts a CSS selector to apply the collapse to. Be sure to add the class collapse to the collapsible element.
The . collapse class indicates a collapsible element (a <div> in our example); this is the content that will be shown or hidden with a click of a button. To control (show/hide) the collapsible content, add the data-toggle="collapse" attribute to an <a> or a <button> element.
To create an accordion that is collapsed by default, we need to set the 'active' property of the jQuery Accordion as false. Syntax: $("#demoAccordion"). accordion({ collapsible: true, active: false});
When you use the accordion in Bootstrap, the point is to wrap the cards in an element with an individual ID, and then target this element as the data-parent of the collapsibles by referring to the id . Using this simple addition, you can make your content display more interactively.
You can use the LocalStorage or cookies. Here is one example with LocalStorage:
$(document).ready(function () {
$('a').click(function() {
//store the id of the collapsible element
localStorage.setItem('collapseItem', $(this).attr('href'));
});
var collapseItem = localStorage.getItem('collapseItem');
if (collapseItem) {
$(collapseItem).collapse('show')
}
})
FIDDLE
To improve the code you can use the bootstrap collapse events: http://getbootstrap.com/javascript/#collapse-usage, e.g.:
$('#myCollapsible').on('show.bs.collapse', function () {
// store the id of the collapsible element
//....
})
The same strategy could be used with cookies: https://github.com/carhartl/jquery-cookie
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With