You should do it yourself by manipulating CSS classes. That is, if a user clicks on some link, then do something (target action), set previous link inactive and new link active.
If your links take you to the server (that is, make page reload), then you can just render active link correctly on the server. Otherwise, if you're doing some client-side stuff (switching tab panes or whatever), you have to use javascript.
You sound like you need to implement a navigation system. If it's complex, it might get pretty ugly and pretty fast.
In this case, you might want to use a plugin that can handle that. You could use navigasmic or simple navigation (I would recommend navigasmic because it keeps the main layer in a view, where it belongs, and not in some configuration)
Many of the answers here have things that will work, or partial answers. I combined a bunch of things to make this rails helper method I use:
# helper to make bootstrap3 nav-pill <li>'s with links in them, that have
# proper 'active' class if active.
#
# the current pill will have 'active' tag on the <li>
#
# html_options param will apply to <li>, not <a>.
#
# can pass block which will be given to `link_to` as normal.
def bootstrap_pill_link_to(label, link_params, html_options = {})
current = current_page?(link_params)
if current
html_options[:class] ||= ""
html_options[:class] << " active "
end
content_tag(:li, html_options) do
link_to(label, link_params)
end
end
It could be made even fancier with argument checking to support &block on the link_to etc.
I m using bootstrap bare theme, here is the sample navbar code. Note the class name of the element -> .nav - as this is referred in java script.
/ Collect the nav links, forms, and other content for toggling
#bs-example-navbar-collapse-1.collapse.navbar-collapse
%ul.nav.navbar-nav
%li
%a{:href => "/demo/one"} Page One
%li
%a{:href => "/demo/two"} Page Two
%li
%a{:href => "/demo/three"} Page Three
in the view page (or partial) add this :javascript, this needs to be executed every time page loads.
In the javascript debugger make sure you have value of 'href' attribute matches with window.location.pathname. This is slightly different than the solution by @Zitrax which helped me fixing my issue.
def active_navigation?(controllers_name, actions_name)
'active' if controllers_name.include?(controller_name) && actions_name.include?(action_name)
end
slim
li class=(active_navigation?(['events'], ['index', 'show'])) = link_to t('navbar.events'), events_path
The code inside the <%= %> is just ruby, and the = means that the result of that code will be displayed on the HTML.Do this for every option you want to add in your navbar and it should work fine.