1

I have been reading a lot on how to highlight / style links to show the user their current page. None of the solutions seem to work. I have a navbar with links such as <a href="/foo/"> and a dropdown with <a href="/foo/bar"> and when the current page is /foo/bar I want to add a class to both links (/foo/ and /foo/bar).

I have tried using the solutions on CSS-Tricks and tried writing my own jQuery but have not been able to select ALL of the correct DOM elements.

Is there a better jQuery solution or a way to do this server-side?

Jeremy Thomas
  • 6,240
  • 9
  • 47
  • 92
  • 1
    Check out [this answer](http://stackoverflow.com/questions/3705898/best-way-to-add-current-class-to-nav-in-rails-3) and [this blog post](http://blog.rudylee.com/2014/01/15/add-current-class-to-website-menu-in-rails/). – Jeff Mar 16 '16 at 15:13
  • Thanks, helped a lot ! – Jeremy Thomas Mar 16 '16 at 17:01
  • only issue is that when `current_route = Rails.application.routes.recognize_path(path)` then `params[:controller] == current_route[:controller]` is true for links from the same controller even if the action is different – Jeremy Thomas Mar 16 '16 at 18:42

1 Answers1

0

Basically, you want to check if your current controller and action are the ones of the links.

Okay, here is some sample code:

application.css (for ease of seeing... use your own):

a.myLink {
   color: blue;
   background: white;
   size: 24px;
}

a.active {
  background: green;
  color: pink;
}

In your helper script (I put mine in application_helper):

module ApplicationHelper
  def active_link?(controller, *action)
    controller.include?(controller_name) && action.include?(action_name)
  end
end

in your layout page (mine is views/layouts/application.html):

<%= controller_name %>
<%= action_name %>
  <br>

  <%= link_to "list articles", articles_path, class:"myLink #{active_link?('articles', 'index') ? 'active' : '' }" %>
  <%= link_to "new article", new_article_path, class:"myLink #{active_link?('articles', 'new') ? 'active' : '' }"  %>
  <br>
  <%= link_to "list posts", posts_path,  class:"myLink #{active_link?('posts', 'index') ? 'active' : '' }"  %>
  <%= link_to "new post", new_post_path,  class:"myLink #{active_link?('posts', 'new') ? 'active' : '' }"  %>

  <%= yield %>

</body>
Jeff
  • 4,285
  • 15
  • 63
  • 115