Ruby on Rails highlight current link on navigation bar?

There are a few approaches to this, but if you're after a simple one, I suggest adding a class to your body.

<body class="<%= params[:controller] %>_controller">
  ...
</body>

Then in your css you can do the following.

body.menus_controller  #navigation a.menunav,
body.drinks_controller #navigation a.drinknav {
  background-color : yellow
  color : blue
}

This can get complicated if you have multiple pages you want to split, but for this basic example it should be ok.


Use a Rails Helper: link_to_unless_current

  • Simple and the fastest.

  • I like @Anatoly's idea to use the link_to_unless_current helper so I whipped up the following solution. Copy and paste to save you some time.:

What does it do?

  • If the page is current then it executes the block - and you can add the CSS classes you need to highlight that link.
  • If the page is NOT current, then it simply returns the first link above.

Hope this helps.


Something like this would work for you. Of course you'd have to tweak it to your purposes, maybe get more sophisticated with the match (currently this would only match paths, as you have in your example).

$("#navigation a[href="+window.location.pathname+"]")
  .closest('li')
    .css('background-color', '#ff0');

Better still, you'd define a "current" class somewhere, then simply add it:

/* in some stylesheet */
#navigation li.current { background-color: #ff0; }

/* then the js */
$("#navigation a[href="+window.location.pathname+"]")
  .closest('li')
    .addClass('current');

The first approach is to handle current controller_name and action_name to detect what page you are on. It's good, but it adds a bit of server-side to client-specific template. The rails helper uses that way is link_to_unless_current. Minimum usage of JS. See an example here

The second is to parse $(location) and directly add a certain class to the selected navigation item to highlight it.

The third (depends on an object) is to build a JS object with current state of entity and add methods to add a class to an active nav. Then you can instantiate this JS class, passing on the object and keeping the logic encapsulated.