Michael Raichelson: Portfolio — Code — Automatic Highlighting of Website Navigation

The portfolio of web, multimedia and interactive works by Michael Raichelson, a web and multimedia designer/developer living in Annapolis, MD

Skip to Navigation Skip to Content

Portfolio — Code — Automatic Highlighting of Website Navigation

Objective: To create a way to dynamically highlight website navigation across an entire site without having to manually adjust each page.

Solution: A JavaScript-based system to check the current page URL against the links in navigation-specific CSS class bearing links. In situations where the current URL matches a navigation link URL a new CSS class is applied to that link. This code highlights top level sections as well as second level pages within them. Thus if a person visits the "Dogs" section of a site and the "Bulldogs" page within that section both "Bulldogs" and "Dogs" will be highlighted.

Technologies Used: JavaScript, HTML, CSS

navigation-highlight.js

An external JavaScript library for containing the navigation highlight function.

function donavhighlights(){
   if(!document.layers){
      var atags=document.getElementsByTagName("a");
      for(var i=0;i<atags.length;i++){
         if(atags[i].className=="nav1"){
            if(document.location.href.indexOf(atags[i].href)!=-1){
               atags[i].className="active1";
            }
         }
      }
      var atags=document.getElementsByTagName("a");
      for(var i=0;i<atags.length;i++){
         if(atags[i].className=="nav2"){
            if(document.location.href.indexOf(atags[i].href)!=-1){
               atags[i].className="active2";
            }
         }
      }
   }
}

Example HTML

This is an example of HTML that is formatted to be highlighted using this script.

<a class="nav1" href="/our_services/">Our Services</a>
<a class="nav2" href="/our_services/accounting/">Accounting Services</a>
<a class="nav2" href="/our_services/tax_services/">Tax Services</a>
<a class="nav2" href="/our_services/payroll/">Payroll Services</a>

Implementation

The JavaScript library is included on the page by using the following code in the <head> section of the HTML page.

<script type="text/javascript" src="/js/navigation-highlight.js"></script>

The JavaScript function then needs to be called on page load to highlight the navigation either by adding it to the <body> tag

<body onload="donavhighlights()">

or attached as an onload event using JavaScript in the <head> of the HTML document.

<script type="text/javascript">
   window.onload=function(){
      donavhighlights();
   }
</script>