To get the accordion to automatically open the correct section based on the URL, you'll start with enabling the navigation
option with something like:
$('#accordion').accordion('option', 'navigation', true);
By default, this option looks for the accordion header link that has an href
that matches the URL fragment (if your URL is http://somesite.com/about#contact, #contact is the fragment) and opens that header link's section. Since you're using the accordion to navigate to different pages, you probably won't have URL fragments to match against, so you'll have to write a custom navigationFilter
:
$('#accordion').accordion('option', 'navigationFilter', function(){ ... });
You can use the navigationFilter
option to override how the accordion plugin matches header links to the URL of the current page.
So far, we've got the right section of the accordion to open based on the current page. Next, we need to highlight the link in that section that corresponds to the page. You'll do that with something like:
<script type="text/javascript">
$(document).ready(function() {
$('#accordion li').each(function() {
var li = $(this);
var a = $('a', li);
if(/* compare the href of the 'a' element to the current URL */) {
li.addClass('active');
}
});
});
</script>
<div id="accordion">
<h3><a href="#">Section 1</a></h3>
<div>
<ul>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</div>
<h3><a href="#">Section 2</a></h3>
<div>
<ul>
<li><a href="/help">Help</a></li>
<li><a href="/faq">FAQ</a></li>
</ul>
</div>
</div>
Here we're going through all the page links in the navigation accordion, picking the one that matches the current URL, and applying an .active
class to it, which you can then style differently with CSS.
An aside: another, probably better, way to accomplish the second part is to build the page with the .active
class already applied to the appropriate link, but that assumes you have control over the backend and that you know how to do it. In fact, if that's the case, you could skip the whole navigationFilter
thing and generate a <script>
block to set the active
option on the accordion to open the right section.