Bootstrap JS Collapse provides base styles and flexible support for collapsible components like accordions and navigation. Some articles below [Bootstrap Multiple Expand/Collapse], I had present a custom jQuery script which based on the given Bootstrap JS Collapse script and actually it was extended with the famous feature expand/collapse all.
In this article, using again the Bootstrap JS Collapse script, I will provide a custom jQuery script that will get url parameter and define the current state of the collapsible element.
More specifically, if you use the accordion example code that is provided by Bootstrap framework, you will be sure that add aria-expanded to control the element. In our case, the use case scenario prescribes that the collapsible elements should be closed by default and only one collapsible element will be open every time regarding a custom url parameter.
The following code presents how I developed the above scenario:
Bootstrap JS Collapse – Accordion Example Code
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-controls="collapseOne">
Collapsible Group Item #1
</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
<div class="panel-body">....</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingTwo">
<h4 class="panel-title">
<a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-controls="collapseTwo">
Collapsible Group Item #2
</a>
</h4>
</div>
<div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
<div class="panel-body">...</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingThree">
<h4 class="panel-title">
<a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-controls="collapseThree">
Collapsible Group Item #3
</a>
</h4>
</div>
<div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree">
<div class="panel-body">....</div>
</div>
</div>
</div>
jQuery Script – Custom Code
//Given a query string "?accPanel=collapseTwo"
//$.urlParam("accPanel") will return "collapseTwo"
$.urlParam = function(name){
var results = new RegExp(name + "=([^&]*)", "i").exec(window.location.href);
return results[1] || 0;
};
$(function(){
//assign the retuern value to params variable
var params = $.urlParam('accPanel');
//on document ready open the respecrtivle collaspible element
$("#"+params).addClass('in');
}
Join the conversation