Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails highlight current link on navigation bar?

Can anyone tell me how to highlight (with color) the current link on a navigation bar, using css? I don't want to use the controller option. Here is the code from shared/menu.html.erb:

 <div id = "navigation">

  <ul>

  <li id="menu"><%=link_to "Menu", menus_path, :class => "menunav"%></li>
 <li id="drink"><%=link_to " Drinks", drinks_path, :class => "drinknav"%> </li>

 </ul>

 </div>
like image 494
blawzoo Avatar asked Sep 25 '11 21:09

blawzoo


2 Answers

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.

like image 107
Anatoly Avatar answered Sep 20 '22 07:09

Anatoly


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');
like image 39
numbers1311407 Avatar answered Sep 18 '22 07:09

numbers1311407