Updating the Header with JQuery after reloading the page

4

I have a Rails partial to load my header on all pages ..

_header.html.erb:

<ul class="nav navbar-nav">
  <li><%= link_to "Home", root_path %></li>
  <li><%= link_to "Top Itens!", itens_path %></li>
    <li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown"> Mais! <b class="caret"></b></a>
    <ul class="dropdown-menu">
      <li><%= link_to "Sobre", sobre_path %></li>
      <li><%= link_to "Privacidade", privacidade_path %></li>
      <li><%= link_to "Termos", termos_path %></li>
      <li><%= link_to "Contato", contato_path %></li>
    </ul>
  </li>
</ul>

JQuery:

$('.nav li').click(function() {
  $(this).siblings('li').removeClass('active');
  $(this).addClass('active');
});

The problem is that every time the page is reloaded, '.nav li' comes back without the active class. How should I proceed?

    
asked by anonymous 09.05.2014 / 03:18

2 answers

0

To do in rails:

<li <%="class='active'" if current_page?(sobre_path) %>>
  <%= link_to "Sobre", sobre_path %>
</li>
    
12.05.2014 / 19:32
1

If there is a way to add the class via Ruby on Rails this seems to me to be the "cleanest" way, and then I have no knowledge.

But you can use the url to make jQuery assign a class to li that has a specific URL.

Example:

var url = window.location.pathname.split("/");
var parteURL = url[url.length - 1] ? url[url.length - 1] : url[url.length - 2];

This code will assign the variable parteURL to the last part of the url, after the last / . Here you can use javascript (jQuery) to iterate all the links and search for what corresponds to them, assigning the class to li its predecessor:

$('.nav li a').each(function () {
    if (~this.href.indexOf(parteURL)) $(this).closest('li').addClass('active'));
});
    
09.05.2014 / 06:01