1 min read

Highlighting current link within a navigation list in rails

Syed Aslam

It's very common to want to highlight the current link within a navigation list for the current action being performed. If you are using Ajax, then this is easy, handle the onclick event to highlight the current link.

<%= link_to 'Home', 'javascript:void(0);',
  :onclick => "this.addClassName('youarehere');this.siblings().each(function(s){s.removeClassName('youarehere');});",
  :class => '', :id => 'home' %>

<%= link_to 'News', 'javascript:void(0);',
  :onclick => "this.addClassName('youarehere');this.siblings().each(function(s){s.removeClassName('youarehere');});",
  :class => '', :id => 'news' %>

Make sure you have a CSS class called youarehere. The following CSS is just an example.

.youarehere {
    font-size: 11pt;
    text-decoration: underline;

If you are not using Ajax, you need to know what the current action and controller is. But how to know what the currect action is (without doing some ugly URL parsing)?

The first thing to do is add the following code to your application_helper.rb< file

def section_link(name, options)
  action      = options[:action] || 'index'
  controller  = options[:controller]
  if action == @current_action && controller == @current_controller
    link_to(name, options, :class => 'youarehere')
    link_to(name, options)

The above method always expects an :controller key to be passed in with the options hash. If you don't pass the optional :action key, it will assume 'index' as the action being performed.

We need to know what the current_controller and current_action is for the above method to work. Finally put this in your application_controller.rb file, as it makes the current executing action and controller name available to the helper.

before_filter :instantiate_controller_and_action_names
def instantiate_controller_and_action_names
  @current_action  = action_name
  @current_controller = controller_name

In your view you have to use:

<%= section_link( "Home", :controller => 'welcome', :action => 'index' ) %>
<%= section_link( "News", :controller => 'news', :ref => 'home' ) %>

Cover photo by Hello I'm Nik