Dynamic highlight in Tumblr navigation bar

Anonymous asks:

How do you dynamically highlight the active page in your navigation bar?

Hi “Anonymous”, thanks for your question.

With the magic of JQuery, it’s pretty simple! My navigation bar presents thusly:

<nav>
    <ul id="navigation">
        <li><a href="/">Home</a></li>
        <li><a href="/about">About</a></li>
    </ul>
</nav>

So, I use a bit of JQuery magic to set .active on the <li>:

function setNavigation() {
   var path = window.location.pathname;

   // strip slashes from path
   path = path.replace(/^\/|\/$/g, ");
   path = decodeURIComponent(path);

   if (path === "") {
       // are we are the homepage? if so, set the active class and finish
       $("#navigation li a[href='/']").addClass('active');
       return false;
   }

   $("#navigation li a").each(function () {
       // otherwise, iterate through navigation bar items,
       // and see if we can find an active <li>
       var href = $(this).attr('href');

       if (path === href.substr(1, path.length)) {
           $(this).addClass('active');
       }
   });
}

$(function () {
   setNavigation();
});

Simple!