Reputation:
I have this JS code for my menu:
$(document).ready(function () {
$('#nav > li > a').click(function(e){
if ($(this).attr('class') != 'active'){
$('#nav li ul').slideUp();
$(this).next().slideToggle();
$('#nav li a').removeClass('active');
$(this).addClass('active');
}
});
});
what is the best way to make the sub menus stay open when the page is changed - maybe using cookies or sessions?
I have created a jsfiddle here so you can see the full html and css etc: http://jsfiddle.net/bMkEj/
Upvotes: 3
Views: 3016
Reputation: 427
Pass a query parameter when you load the page and use it to select the appropriate nav item:
<ul>
<li id="foo"><a href="index.html?nav=foo">Foo</a>
<ul>
<li>Foo 1</li>
<li>Foo 2</li>
</ul>
</li>
<li id="bar"><a href="index.html?nav=bar">Bar</a>
<ul>
<li>Bar 1</li>
<li>Bar 2</li>
</ul>
</li>
<li id="baz"><a href="index.html?nav=baz">Baz</a>
<ul>
<li>Baz 1</li>
<li>Baz 2</li>
</ul>
</li>
</ul>
$(document).ready(function() {
var query = decodeURIComponent(window.location.search);
var matches = query.match(/nav=([^&]*)/);
var id = matches[1];
$('#' + id + ' ul').slideDown();
});
Upvotes: 1
Reputation: 64526
It can be done using HTML5 LocalStorage.
In the click handler, save the active menu text to localStorage:
$('#nav > li > a').click(function(e){
...
localStorage.setItem("activeSubMenu", $(this).text());
});
On page load, read the localStorage and expand the menu (if found):
$(document).ready(function(){
var activeItem = localStorage.getItem("activeSubMenu");
if(activeItem){
$('#nav > li > a').filter(function() {
return $(this).text() == activeItem;
}).slideToggle();
}
});
Upvotes: 3
Reputation:
If you're running PHP, or any other server-end language, you could add the active class to the active element.
EDIT: If you're just running JS you might be able to parse the url (window.location.href) and use that to set the active class.
Upvotes: 0