I'm building a static website in Ruby on Rails and I have an application.html.erb file that looks like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BayEquities</title>
<%= stylesheet_link_tag "application", :media => "all" %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
<%= render "layouts/shim" %>
</head>
<body>
<%= render "layouts/header" %>
<div class="container">
<%= yield %>
</div>
</body>
</html>
<script type="text/javascript">
$(function() {
$('.navbar .nav > li > a').click(function(e){
$('.navbar .nav > li.active').removeClass('active')
$(this).parent('li').addClass('active')
});
});
</script>
Currently this code adds the active class and removes it accordingly. The only issue is that the header partial (code below) reloads every time a new navbar link is clicked. Thus applying the active class to "Home" after every click.
_header.html.erb
<header class="navbar">
<div class="navbar-inner">
<a class="brand" id="logo">Bay Equities</a>
<ul class="nav">
<li class="active"><%= link_to "Home", "index" %></li>
<li><%= link_to "Services", "services" %></li>
<li><%= link_to "Contact Us", "contact" %></li>
</ul>
</div>
</header>
I apologize in advance for the rushed formatting job, thanks for all the help!
Have you considered moving this logic to rails?
For example you could setup a helper method that assigns the active class based on params[:action].
module ApplicationHelper
def is_active(action)
params[:action] == action ? "active" : nil
end
end
And then in your partial for your home link:
<li class="<%=is_active('home')%>"><%= link_to "Home", "index" %></li>
<li class="<%=is_active('services')%>"><%= link_to "Services", "services" %></li>
<li class="<%=is_active('contact')%>"><%= link_to "Contact Us", "contact" %></li>
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