1

Hello i want to ask why my code doesn't work. I use ruby on rails with bootsrap and haml.

Here is my javascript code:

:javascript
  $(".nav navbar-nav li a").click(function() {
    $(this).parent().addClass('active').siblings().removeClass('active');
  });

And here is my navigation bar's code:

%nav.navbar.navbar-inverse
  .container-fluid
    .navbar-header
      %img.image{:alt => "Ruby Logo", :src => "http://www.rossconf.io/images/projects/ruby-2779abad.png"}
      = link_to "Users", users_path, class: 'navbar-brand'
      #bs-example-navbar-collapse-1.collapse.navbar-collapse
    %ul.nav.navbar-nav
      %li
        %a{:href => addresses_path}
          Addresses
          %span.sr-only (current)
      %li
        %a{:href => imports_path}
          Import addresses
          %span.sr-only (current)
      - if current_user     
        %li
          %a{:href => logout_path}
            Logout
            %span.sr-only (current)
      - else
        %li
          %a{:href => login_path}
            Login
            %span.sr-only (current)

Any idea why it runs without errors but nothing happens? Active class is not added to li element.

Titas Kurtinaitis
  • 299
  • 1
  • 4
  • 13

2 Answers2

1

I guess there's a mistake in your code:

It should be:

$(".nav.navbar-nav li a").click(function() {
//-----^^-------missed a class selector here and you can see a space too 
    $(this).parent().addClass('active').siblings().removeClass('active');
}); 
Jai
  • 74,255
  • 12
  • 74
  • 103
Prabhas Nayak
  • 282
  • 1
  • 4
1

First you miss the joining the class in selector. Second thing is if you are want to add active class when you click link then there is two possible solutions are :-

First Solution is

$(".nav .navbar-nav li a").click(function(event) {
  event.preventDefault();
    $(this).parent().addClass('active').siblings().removeClass('active');
  });

Second Solution is :-

 $(function() {
     var pgurl = window.location.href.substr(window.location.href
.lastIndexOf("/")+1);
     $(".nav .navbar-nav li a ").each(function(){
          if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
          $(this).addClass("active");
     })
});

please tell me if i'm wrong and not meet requirement

Manjeet Thakur
  • 2,288
  • 1
  • 16
  • 35
  • I've tried first solution already because other people told me that. Unfortunately, second solution doesn't work too. Its good to mention that i am working on localhost, but i think problem isn't here. Don't know what to do next... – Titas Kurtinaitis Oct 13 '15 at 10:12
  • please can you tell that you links are changed when you click on menu item.Second solution is valid only if your links are changed. – Manjeet Thakur Oct 13 '15 at 10:14
  • 1
    Please see this answer [link] (http://stackoverflow.com/questions/20060467/add-active-navigation-class-based-on-url) – Manjeet Thakur Oct 13 '15 at 10:20