Updating Header with Jquery after page reload

Asked

Viewed 266 times

4

I have a partial in Rails to load my header in 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' returns without the active class. How should I proceed?

2 answers

1

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

However, 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 to the variable parteURL the last part of the url, after the last /. There you can use javascript (jQuery) to iterate all links and find what matches it, assigning the class to the li its predecessor:

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

0


To do in Rails:

<li <%="class='active'" if current_page?(sobre_path) %>>
  <%= link_to "Sobre", sobre_path %>
</li>
  • Ball show worked right! Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.