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>
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With