Skip to content

Instantly share code, notes, and snippets.

@krciga22
Created March 3, 2013 18:43
Show Gist options
  • Save krciga22/5077561 to your computer and use it in GitHub Desktop.
Save krciga22/5077561 to your computer and use it in GitHub Desktop.
Use this JavaScript class to quickly add css state to an html menu with a tag links. Once initiated, the class will look at all a tags within the main menu element specified and will append the class name 'selected' to the a tag representing the current page. *Please note this is not for ajax based menus.
/**
* Use this class to quickly add css state to an html menu with a tag links.
* Once initiated, the class will look at all a tags within the main menu element
* specified and will append *the class name 'selected' to the a tag representing
* the current page. Please note this is not for ajax based menus.
* @class ANF_StatefulMenu
* @author ANF.
* @example
// menu initiation script (requires jQuery to be loaded so place in your html code near the closing body tag)
<script type="text/javascript">
var mainMenu = new ANF_StatefulMenu({
'menuId': 'mainMenu'
,'linkAliases': [
['home', 0]
['subpage.html', 1]
['subpage2.php', 2]
['subpage3', 3]
]
});
<?script>
*/
var ANF_StatefulMenu = function(config){
var className = "ANF_StatefulMenu";
// check for jquery first
if(typeof jQuery == 'undefined'){ alert(className+' Requires jQuery to work.'); return; }
// check for configuration
if(typeof config == 'undefined'){ alert(className+' Requires configuration to work.'); return; }
// check for required params
var requiredParams = new Array('menuId');
for(var j=0; j<requiredParams.length; j++){
var requiredParam = requiredParams[j];
if(typeof config[requiredParam] == 'undefined'){ alert(className+' Requires Parameter ('+requiredParam+') to work.'); }
}
// loop through the menu's elements and select the link (a tag) that represents the current page
var menu = $('#'+config.menuId);
var linkAliases = config.linkAliases;
var menuItems = $('#'+config.menuId+' a');
var selectedMenuItemFound = false;
for(var i=0; i<menuItems.length; i++){
var menuItem = menuItems[i];
menuItem.menu = menu;
if(selectedMenuItemFound){continue;}
if(location.href == menuItem.href){
menuItem.className += 'selected';
selectedMenuItemFound = true;
}
}
// if none of the links represent the current page, check and see if any of our alises do
if(!selectedMenuItemFound && typeof linkAliases != 'undefined'){
for(var j=0; j<linkAliases.length; j++){
var linkAlias = linkAliases[j];
var linkAliasHref = linkAlias[0];
if(location.href.search(linkAliasHref+'$')!=-1){
menuItems[linkAlias[1]].className += 'selected';
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment