I have a layout with a menu navigation. I’m using a template I found online. There is an HTML page for each menu item and the li item class is called “selected” for each corresponding page. It looks like this:
<nav>
<ul class="sf-menu" id="nav">
<li class="selected"><%= link_to "home", root_path %></li>
<li><%= link_to "about me", about_path %></li>
<li><%= link_to "my portfolio" %>
<ul style="z-index: 2;">
<li style="z-index: 2;"><%= link_to "portfolio one", portfolio_one_path %></li>
<li style="z-index: 2;"><%= link_to "portfolio two", portfolio_two_path %></li>
<li style="z-index: 2;"><%= link_to "portfolio three", portfolio_three_path %></li>
</ul>
</li>
<li><%= link_to "blog", blog_path %></li>
<li><%= link_to "contact", contact_path %></li>
</ul>
</nav>
So this is in my application.html.erb file. My question is how do I programmatically change each li item’s class to “selected” depending on which link the user clicks on? Can this be done with Ruby or do I need to use JavaScript?
I think you want the
current_page?helper method – http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-current_page-3F