Automatically Highlight Current Page in Navigation with CSS & jQuery

August 3, 2010 Filed under: CSS,jQuery

It’s common that we want to highlight the current page in navigation to tell users where they are now, and it’s very easy to do it with CSS. Just by adding a class “highlight” to < li > tag and write the style we want in stylesheet. Let’s start it with a simple page:

HTML markup
<ul class="navigation">
<li><a href="index.html">Home</a></li>
<li class="highlight"><a href="product.html">Product</a></li>
<li><a href="about.html">About</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
Style Sheet
<style type="text/css">
a, a:visited{color:#000; font-weight:bold; text-decoration:none;}
ul.navigation{list-style:none; font: 0.75em/1.5em normal Tahoma, Verdana, Geneva, sans-serif;}
ul.navigation li{ background:#ececec; margin:1px;padding:5px 15px; display:block; float:left;}
ul.navigation li.highlight{ background:#666;}
ul.navigation li.highlight a{ color:#f5f5f5; cursor:default;}
</style>

Then, we will get a page look like this:

screenshot of highlight navigation

However, we have to change class “highlight” position in each page in order to show the highlight link correctly. It’s not convenient when we have a complicated navigation, and how about when we have to write php/asp templates or .net masterpages? Can we use exactly same html code in each page but highlight the navigation link automatically? The answer is YES. Few lines of jQuery code will simply does the trick. Let’s still paly with this simple page to explain the idea.

  1. Link the jQuery library to these pages
  2. Leave the highlight class at home link’s container <li> to make it as the default highlight link. *
  3. Write jQuery code

*It’s because we use the strategy of getting the current url and comparing it with the links in navigation until the link’s href is found, then add “highlight” class to the link’s container <li>. If we don’t make the Home link as the default highlight link, when user www.yourdomain.com to open the website, the url doesn’t contain any links of the navigation, so, nothing would be automatically highlight.

HTML markup
<script src="http://code.jquery.com/jquery-latest.js"></script>
<ul class="navigation">
<li class="highlight"><a href="index.html">Home</a></li>
<li><a href="product.html">Product</a></li>
<li><a href="about.html">About</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
jQuery code
$(document).ready(function(){
var str=location.href.toLowerCase();
$(".navigation li a").each(function() {
if (str.indexOf(this.href.toLowerCase()) > -1) {
 $("li.highlight").removeClass("highlight");
$(this).parent().addClass("highlight");
}
 });
 })

OK, we have it done here since this is just a very simple page.
View the Demo Pages
Download the Demo pages

In reality, we always have much more complicated situations. What can we do if we have child navations? We not only want to highlight the child navigation’s link but also the parent container <li>. The simple method is searching the highlight <li>’s parent elements, if the parent elements are <li>, add “highlight” class to this <li>.

HTML markup
<script src="http://code.jquery.com/jquery-latest.js"></script>
<ul class="navigation">
<li class="highlight"><a href="index.html">Home</a></li>
<li><a href="product.html">Product</a>
<ul class="childNav">
<li><a href="laptop.html">Laptop</a></li>
<li><a href="camera.html">Camera</a></li>
<li><a href="phone.html">Phone</a></li>
</ul>
</li>
<li><a href="about.html">About</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
jQuery code
$(document).ready(function(){
var str=location.href.toLowerCase();
$(".navigation li a").each(function() {
if (str.indexOf(this.href.toLowerCase()) > -1) {
$("li.highlight").removeClass("highlight");
$(this).parent().addClass("highlight");
}
});
$("li.highlight"').parents().each(function(){
if ($(this).is("li")){
$(this).addClass("highlight");
}
});
})

View the Demo Pages
Download the Demo pages

Cross Browser: Firefox 2+, IE 6+, Safari 3+, Opera 9+, Chrome

{43 Comments}

  1. Donna Says:

    Youre so cool! I dont suppose Ive read anything like this before. So nice to find somebody with some original thoughts on this subject. realy thank you for starting this up. this website is something that is needed on the web, someone with a little originality. useful job for bringing something new to the internet!

  2. Prianca Says:

    Hi there, just became aware of your blog through Google, and found that it is truly informative. I’m gonna watch out for brussels. I’ll be grateful if you continue this in future. Many people will be benefited from your writing. Cheers!

  3. Jessie Says:

    Thanks for the comments! I’m very glad that it helps and you guys encouraged me to continue this blog.

  4. Saeid A.K Says:

    hey dude, really thanks …. tnx tnx tnx tnx I’d need it very much ! my latest problem is solved !! thank you very much

  5. ElecTechGenius Says:

    Great post Jessie.

    I’m fine tuning the design of a new site I’m working on. It’s a passionate area of mine and I’ve got lots and lots of content already written and ready to go. All that’s lacking is the platform (site design) to present the info. Your post has definitely made my job easier. I have a spry horizontal nav bar similar to the second example you provided. You can’t believe how many hours I’ve wasted trying to find a script that will function as per your example above. I’d just like to second the sentiments a post above regarding actually putting something on the web that is useful.

    Great job, keep the blog going strong and solidly. I am definitely subscribing to it.

    Best regards.

  6. Kawsar Ali Says:

    Hey, Thanks for this. Used it.

  7. Clearbytes. Says:

    Only version of this code I’ve found which works perfectly… thank you.

  8. supergarEo Says:

    Hey thanks for this, i have a question for ElecTechGenius. How did you get this to work within you spry horizontal nav menu.

    Any help on configuring this to work with spry horizontal nav menu would be gratefull.

    Thanks

  9. Vedran Sadic Says:

    Hi!

    How to remove class=”highlight” from the default HOME LINK after another page is selected?

    Thanks!

  10. Jessie Says:

    Hi Vedran, sorry for I forgot remove the default one. I’ve modified the code, please see the code in this post. Thanks!

  11. Giles Says:

    Hi, this seems to have a bug in Safari? Works well in Firefox but the background doesn’t corespond??

  12. Jessie Says:

    For what I can see, it does work in Safari…

  13. Eel Says:

    Grade A stuff. I’m unquestioanlby in your debt.

  14. Zariel Says:

    I didn’t know where to find this info then kaobom it was here.

  15. Tangela Says:

    Thanks for introducing a little rationality into this dbetae.

  16. sagun shrestha Says:

    i agree with the above codes. Can you provide me the coder for the horizontal one.

  17. sagun shrestha Says:

    can you provide me the solution for the last one for vertical menu.

  18. siri Says:

    thanks dude! big help!

  19. Ronni Says:

    I loved your code, thank you.

    To adapt to my need, I removed the Default Home.

    Here’s the code:
    var str=location.href.toLowerCase();
    $(‘.navigation li a’).each(function() {
    if(str==this.href.toLowerCase()){
    $(“li.highlight”).removeClass(“highlight”);
    $(this).parent().addClass(“highlight”);
    }
    });

  20. Shaikh Salman Says:

    I loved your code, thank you very much.

  21. Yashwant Says:

    Tnx for share ur ideas Good Job !!!

  22. Cy Heldstrom Says:

    Very elegant and clean solution! Thanks for making this easy!!

  23. Sue Says:

    Thanks for the code! Question. Is there any way to get this to work on the same page with a Nivo slider? The highlighting shows up perfectly but now the slider won’t work.

  24. Tellem Says:

    thank you :) it helped me

  25. XRumerTest Says:

    Hello. And Bye.

  26. Tanaji Chavan Says:

    Thanks a lot Jessie this is what exactly i was looking for … IT works for me
    Keep the good work up :)

  27. Ibanga Says:

    Very cool stuff. Very effective yet so light and easy. Thanks.

  28. social bookmark submission Says:

    I really enjoy the post. Keep writing.

  29. best social bookmarking Says:

    Very informative article post.Really thank you! Will read on…

  30. lose weight pills Says:

    EI8khI Thank you ever so for you blog.Thanks Again. Really Great.

  31. john Says:

    A MILLION thanks!!! You saved the day. :)

  32. kapil Says:

    nice work, but why not working on safari v.5.1.7

  33. buy clomid no prescription Says:

    XKP4mj Major thanks for the blog article. Really Great.

  34. Muthiulhaq Says:

    thank you very much…..

  35. Ron Says:

    Thanks, works great!

  36. Miguel Says:

    Hello nice work is there a way if i click an article for example it keeps on the latest selected menu instead of reseting to the home link on the menu?

  37. smartpc Says:

    How do I make the submenu horizontal instead of Vertical?
    Thanks in advance.

  38. MCM 財布 Says:

    There are lots of advantages of working from your home on eBay. You can start up an at your home business with very minor capital invested. Additionally you can work your own hours.

  39. Dave Hanaford Says:

    Awesome, thanks for this!

  40. sraprui Says:

    nice

  41. Ryan Burnett Says:

    This works great for top-level pages.

    Any idea how to get this working with sub pages?

  42. cheap jerseys Says:

    It is immediately available

  43. rajiv Says:

    good work .its working nicely .thankx

Leave a Reply

IMPORTANT!

To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)

Please leave these two fields as-is:

© All right reserved by Jessie Su. Powered by WordPress