Users must always know where they are within a Web site and where they are visually on the navigation menu. This basic user interface requirement can be overlooked and often is. I have seen few solutions in jQuery or JavaScript for this issue — most solutions often involve backend programming using PHP, JSP, or ASP. The following tutorial guides you through how to set up active menu items on your Web site's navigation menu using jQuery. The jQuery script is set up to determine the selected element in the menu based on the address in the URL.
1. Create a variable named path and set its value to location.pathname, which is part
of the location object in native JavaScript. It returns everything after the domain name.
var path = location.pathname;
Assume that we are currently on this page: www.domainname.com/mycode/delphinidin.html. The location.pathname is equal to /mycode/delphinidin.html.
2. Create another variable name pathArray and use the native split() method from native JavaScript to split the path string using the '/' into an array.
var pathArray = path.split('/');
Th e result of pathArray is ['mycode', 'delphinidin.html']. Th is result is reached by the splitting the value of path (/mycode/delphinidin.html) into two separate strings.
3. Create a final variable and set the value to the length of pathArray.
var pArrLength = pathArray.length;
4. Set up a for loop to iterate through the values in the array. Using the attribute selector, set up a selector statement to match all anchor tags that contain a value from pathArray and add the class selected. Th e attribute selector that is specified here uses the wildcard select, which matches the value in any part of the href:
for(i=0; i < pArrLength; i++) {
$("a[href*='"+pathArray[i]+"']").addClass("selected");
}
Th e active menu item script is limited and works in situations only where there is a navigation menu with no drop-down. When a drop-down menu is added and you would like to highlight a menu item that is a parent of the page you are on, you need to alter the script to not only highlight the top-level pages, but also the children of these top level pages. For example, if you had a top-level item called About Us and under this drop-down list were items such as Our Story, Careers, and Contact Us, which are considered children of the top-level item, you would need to use parent() and children() selectors and build an array of possible URL matches to set this up.
0 comments:
Post a Comment