简体   繁体   中英

how to change active items ? in Materialize navbar

I'm not so good in Js and Jquery, and I'm looking for changing active items by changing li active class, in Materialize navbar. I have tried this:

    <nav>
    <div class="nav-wrapper">
      <a href="#" class="brand-logo right">Logo</a>
      <ul id="nav-mobile" class="left hide-on-med-and-down">
        <li class="active"><a  href="{{path('marianna_mv_Accueil')}}">Accueil</a></li>
        <li><a href="{{path('marianna_mv_APropos')}}">Á propos de moi</a></li>
        <li><a href="{{path('marianna_mv_CeQueJePropose')}}">Ce que je propose</a></li>
        <li><a href="{{path('marianna_mv_Bibiliographie')}}">Bibliographie</a></li>
        <li><a href="{{path('marianna_mv_Contact')}}">Contact</a></li>
      </ul>
    </div>
  </nav>

script

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

But it doesn't work

Didn't you forget to add jquery with your project? I think your code is okay.

Edit: when I set the value of a>href to "#" it works, but when I put the url as mentioned above It doesn't work.

When I put the URL, I notice that it works when the page is loaded but quickly the active class is back in the initial li, and disappear in the current li for the current page.

Someone know how to keep the active class with the url in li a>href ?

I solved the problem by using a switch on "window.location.pathname" this way:

     <nav>
    <div class="nav-wrapper">
      <a href="#" class="brand-logo right">Logo</a>
      <ul  id="nav-mobile" class="left hide-on-med-and-down">
        <li id="ac" ><a  href="{{path('marianna_mv_Accueil')}}">Accueil</a></li>
        <li id="ap" ><a href="{{path('marianna_mv_APropos')}}">Á propos de moi</a></li>
        <li id="cp" ><a href="{{path('marianna_mv_CeQueJePropose')}}">Ce que je propose</a></li>
        <li id="bi" ><a href="{{path('marianna_mv_Bibiliographie')}}">Bibliographie</a></li>
        <li id="cn" ><a href="{{path('marianna_mv_Contact')}}">Contact</a></li>
      </ul>
    </div>
  </nav>



      {% block body %}
      {% endblock %}

   <script>
 //alert(window.location.pathname);    
switch (window.location.pathname) {
    case '/':
        $('#ac').addClass('active')
        break;
    case '/apropos':
        $('#ap').addClass('active')
        break;
    case '/ceQueJePropose':
        $('#cp').addClass('active')
        break;        
    case '/bibliographie':
        $('#bi').addClass('active')
        break;
    case '/contact':
        $('#cn').addClass('active')
        break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM