Warning: gzinflate() [function.gzinflate]: data error in /home/boozkerc/public_html/kneedeepincode/wp-includes/http.php on line 1787

setnav

Have you ever wanted to change the active state of web site’s navigation but didn’t want to write server side code for it? For example, in PHP, you’d have to write a switch or if/else conditional. Something like:

<?php
   if($current_page == 'home'){
      echo '<a href="/home" class="active">Home</a>';
   }
   else{
      echo '<a href="/home" class="active">Home</a>';
   }
   if($current_page  == 'about'){...}
?>

And so forth for every page. Of course you can do this many other ways, but this was the first way that I was taught. I did it this way for quite awhile just because I thought that this was the right way. However, I started learning JavaScript and jQuery and I wanted to see if there was a way to do it with a few lines of jQuery and make it dynamic so that you would not need to know the pages ahead of time. I did it like this (thanks to @stevejt for the 1 liner):

$(function(){ // Start up jQuery
   $('nav a[href^=/'+window.location.href.split('/')[3].split('#')[0]+']').addClass('current_page');
});

When I’m either not using a CMS or a CMS doesn’t offer very good support for marking sub pages’ parents (like Concrete5) I use this. I’m using this on http://projectdeploy.org/api actually :)

[Post to Twitter]   [Post to Delicious]   [Post to Digg]   [Post to Reddit]   [Post to StumbleUpon]  

Steve Thompson 27.07.09

You could reduce that down to:

$(function {

$(’.nav a[href^=/'+window.location.href.split('/')[3].split(’#')[0]+’]').addClass(’current_page’);

});

Since you only need the with the matching href. The ^ before the = also lets you select the right nav item if you are in that section or have a trailing slash. It would match:
about/
about
about/company/
about/index.html

Steve Thompson 27.07.09

Oh and that was an example for a .nav not a HTML 5 nav that I gave, FYI.

Michael Acevedo 09.12.10

I’m trying to make a side navigation item become active when the user scrolls up/down the page… how could I do that in jquery?