Wednesday, August 1, 2012

HTML5+jQuery+CSS3 Highlight Selected Nav Item

After looking around the net I found that there were a number of ways to highlight the current item on a navigation menu. However, most of them seemed to be very rigid and written for a certain HTML structure. After finding this, I decided to write a simple jQuery script that allows the UX (User eXperience) to display as expected while using HTML5 coding practices. Here is the code for the script...

Script

/******************************************************
 * Listen for click event and set nav item to selected
 ******************************************************/
 var $navSets = $('nav'),
 //var $navSets = $('#navContainer'),
 $navLinks = $navSets.find('a');

 $navLinks.live('click', function(){
  var $this = $(this);
    
  if($this.hasClass('selected')) {
   return false;
  }

  var $navSet = $this.parents('nav');

  $navSet.find("a.selected").removeClass('selected');
  $this.addClass('selected');
 }); // End navLinks.live / click

The setup is pretty straight forward.

HTML Code

<nav>
    <ul>
        <li><a href='javascript:void(0);'>HOME</a></li>
        <li><a href='javascript:void(0);'>PORTFOLIO</a></li>
        <li><a href='javascript:void(0);'>ABOUT</a></li>
    </ul>
</nav>

The beauty of this is that you can add as many items that you want in the navigation and not have to worry about the page that's being called via AJAX to avoid a page refresh. Also, the nice thing about loading content with AJAX is that you only load the content you want to. While this isn't really SEO friendly, it does make for a great experience for the user.