Web Development Quick Tip: Highlighting the Current Page in Your Navigation Links

Posted by Jeff Edsell on Aug 18, 2011 in Uncategorized |

Here’s a bit of jQuery I use pretty regularly:

    var pathname = window.location.pathname;
    var path = pathname.split('/');
        path[path.length-1] = 'index.php';

    $('#nav a').each(function(){
    if($(this).attr('href') == path[path.length-1]){
        document.title = document.title + ': ' + $(this).text();

It grabs the filename of the page you’re currently on, then runs through your navigation links (in this case they’re inside an element with the id nav) and compares what they link to. If it matches, it adds the class current to the link. This way the page automatically highlights the current page in the navigation.

For extra points, it takes the text of the link and adds it to the page title after a colon. So if every page of your site was titled “ACME”, and you followed the About Us link, the title would automatically change to “ACME: About Us”.

1 Comment

Brent Billock
Aug 18, 2011 at 3:18 pm

Thank you! I knew there had to be a simpler way to automate this.

I’m clipping to my resources folder right now.



Copyright © 2020 Jeff Edsell All rights reserved. Theme by Laptop Geek.