14 4 / 2012

Highlighting navigation links with javascript

Recently I blogged about Tagging the HTML tag. The general idea is to apply some data- attributes to html tag in order to more easily target the page from css and js files. I also blogged about Javascript Processors, technique to keep your “DOM enhancers” organized.

Using the two, here is how you can very easily implement processor that would highlight active link in your navigation. Lets say that we have following nav element:

<nav class="main">
  <a class="home">Home</a>
  <a class="projects">Projects</a>
  <a class="account">My Account</a>
</nav>

Here is how our NavHighlighter may look like:

@NavHighlighter =
  mapping:
    "nav.main .home":      [ /^\/welcome/ ]
    "nav.main .projects":  [ /^\/projects/ ]
    "nav.main .account":   [ /^\/registrations\/(edit|update)/, /^\/profile/ ]

  process: ->
    for elem, paths of @mapping
      $(elem).addClass("active") if App.onPath.apply(App, paths)

We’re using mapping hash to define highlight conditions for each link. Hash key is just css selector, so you can use anything you want. Hash value is an array representing list of paths for which the given link is active.

Can’t we do it on server? Sure. There are two reasons I’m doing it on the client: cleaner and faster erb template, and fragment caching.

What about users with js disabled? Well, they could probably live without highlighted menu items. If you really want to do this on server and still use caching, read more on Cache Personalization.