How to activate a navigation item dynamically

0

I've always tired of changing navbar of all my pages, and I've decided to create a file for navbar and always give include on the pages to make adding / removing items easier!

But, my question is whether to make a system in PHP or JavaScript that can identify the page to set the class 'active' in <li> of navbar corresponding to current page! p>

The NavBar code is as follows:

<div class="container">

<nav class="navbar navbar-inverse">

  <div class="container-fluid">

    <div class="navbar-header">

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-2">

        <span class="sr-only">Toggle navigation</span>

        <span class="icon-bar"></span>

        <span class="icon-bar"></span>

        <span class="icon-bar"></span>

      </button>

    </div>

    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-2">

      <ul class="nav navbar-nav">

        <li class="active clash"><a href="/">Início</a></li>

        <li class="clash"><a href="/ferramentas/gerador-de-emblema">Gerador de Emblemas</a></li>

      </ul>

      <ul class="nav navbar-nav navbar-right">

      </ul>

    </div>

  </div>

</nav>

</div>

For example, I'm on page HOME ! Let's say that id of body is "1" . A script could capture this id and assign the class active to <li> to "1" !

    
asked by anonymous 20.10.2016 / 04:09

1 answer

1

A simple and effective option is to compare the url's return with the href value in its navigation menu, applying the class to the element when the condition is satisfied.

Solution in PHP (comparing url with href)

<?php $paginaLink = $_SERVER['SCRIPT_NAME'];?>
<li>
  <a href="/blog/"
  <?php 
    if($paginaLink == '/blog/index.php') {echo 'class="ativo"';}
  ?>>
  Blog</a>
</li>

This is not one of my preferred solutions because it ends up messing up the HTML of the menu, but it is very simple and effective.

JQuery solution (Comparing attributes)
Taking advantage of your line of reasoning, you can also solve your problem using JQuery by comparing for example if the value of the name property of the <body> of your page is equal to the value of the name property of each <li> of the menu of navigation.

$("nav ul li").each(function() {
  var page_name = $("body").attr("name");
  var menu_name = $(this).attr("name");
  if(page_name == menu_name){
    $(this).addClass("active");
    return false;  
    // retornando false vc evita que o loop continue iterando,
    // supondo que seu menu não precise de 2 itens com classe ativa
  }
});
    
20.10.2016 / 05:10