Nav/subnav List, How To Give Clicked Item Active Class After Reload Of Page
I have a couple nested & hidden sub-nav lists
Solution 1:
$(document).ready(function()
{
// Get the name of the page. Split the URL at the '/':s and get the last part// with pop():var pageName = (location.pathname).split('/').pop();
// If we couldn't get a page name, default to index.html:if( pageName == '' )
{
pageName = 'index.html';
}
// Hide ul:s that are children of the navigation:
$('.nav ul').hide();
// Event handler for clicks on navigation links:
$('.nav a').on('click', function()
{
// Change visibility for the first ul-child of the current li.// $(this) refers to the clicked element.
$(this).parent('li').find('ul').first().toggle();
// Hide other sub-menus:
$(this).parents('li').siblings('li').children('ul').hide();
});
// Search through all link elements in the nav menu:
$('.nav').find('a').each(function(index, value)
{
// Append a '$' to the pagename to make the match()-function search// from the end of the href value:
pageName += '$';
if( value.href.match(pageName))
{
// If the pagename matches the href-attribute, then add the 'active'// class to the parent li, and show parent ul:s:
$(this).parent('li').addClass('active').parents('ul').show();
}
});
});
Solution 2:
You could use a Cookie to hold the value of the currently open menu. This will allow for the value to be saved/retrieved between page loads and browser sessions.
As you've already got jQuery setup you can use the jQuery Cookie plugin to simplify things.
The code for it is quite simple (more examples on plugin page).
$.cookie('open_menu', 'projects'); //Save 'projects' under 'open_menu'$.cookie('open_menu') //Returns 'projects'
Just check the value on page load and save it when one of the menu's is clicked.
If you'd prefer not to add any extra plugins here's some documentation on JavaScript's inbuilt cookie API.
Edit: I've created a JSFiddle with an example for you. The Cookie code doesn't seem to work in there sandbox, but the code should work for you, let me know if you have any troubles.
$(window).load(function() {
if ($.cookie('show_menu') !== undefined) {
$('#' + $.cookie('show_menu')).click();
}
$('.nav > li > ul').each(function () {
//Hide the sub lists
$(this).hide();
//Get link with same ID as Classvar id = $(this).attr('id');
//When link is clicked
$('.' + id).click(function () {
//Get the sub listvar list = $('#' + $(this).attr('class'));
//Check if it's currently visibleif (list.is(':visible')) {
list.hide(); //Hide list
$.cookie('show_menu', ''); //Unset open menu
} else {
$('.nav > li > ul').hide(); //Hide all other lists
list.show(); //Show list
$.cookie('show_menu', list.attr('class')); //Set open menu
}
});
});
});
Post a Comment for "Nav/subnav List, How To Give Clicked Item Active Class After Reload Of Page"