Using JavaScript to Style Active Navigation Elements

Published April 28, 2009 by saurav.roy.

active navigation element

I’m all about efficiency when I’m writing web code. Any time I find myself writing the same functionality more than once or twice, I try to consider whether my repeated code could be wrapped into a function of some sort.

Navigation is often one of those areas where I try to improve my efficiency. I like my navigation elements to pull double duty. I want them to:

  1. Show the user where they can go, and
  2. Show the user where they currently are.

In other words, I want some sort of visual indication in my navigation that shows my user which section of my site they’re in. You can see this on the CSS Newbie site: if you click on the TOC (Table of Contents) link in the bar at the top of the page, you’ll see that link gets special styling when the table of content loads.

Now, I could manually set this on every page using a CSS class. But that’s inefficient — depending on the size of my site, I could end up writing dozens or hundreds of lines of one-off code. And why go to all that work, when you could just wrap it all up into a nice JavaScript function? Read On…

Share and Enjoy !

0Shares
0 0