Highlight current page button based on another page

Asked

Viewed 86 times

0

I have the bottom menu, which is contained in the page empresas.php and "Edit" a company becomes editar-empresa.php?id=x:

inserir a descrição da imagem aqui

The function that adds the class active to the current page is the following:

(function() {
    var nav = document.getElementById('menu'),
        anchor = nav.getElementsByTagName('a'),
        current = window.location.href.split("?")[0];
        for (var i = 0; i < anchor.length; i++) {
            if(anchor[i].href.split("?")[0] == current) {
                anchor[i].children[0].className = "active";
            }
    }
})();

That is, the "Companies" section will only remain highlighted if it is on the page empresas.php, but I need you to remain detached when going to the subsection editar-empresa.php?id=x. What must I do to achieve such a goal?

HTML:

<div id="menu">
    <nav>
        <ul>
            <a href="emissor-nfe.php"><li>Emissor NF-e</li></a>
            <a href="empresas.php"><li>Empresas</li></a>
            <a href="clientes.php"><li>Clientes</li></a>
            <a href="produtos.php"><li>Produtos</li></a>
            <a href="transportadoras.php"><li>Transportadoras</li></a>
            <a href="logout.php"><li>Sair</li></a>
        </ul>
    </nav>
</div>
  • If you can change the file name to editar-empresas.php, could do something like if (current.indexOf(anchor) >= 0). Thus the text would be sought empresas.php in editar-empresas.php and, if you think, define as active, but I do not know if it is a very good solution.

  • Hello @Andersoncarloswoss, could further detail your solution?

  • As soon as I get some free time I’ll see if I can give you an answer.

  • 1

    Remembering that using elements a within a ul is syntactically and semantically wrong. If your goal is to make the whole li respond to the link event, see this reply: https://answall.com/a/221187/5878

1 answer

0

Following @Andersoncarloswoss' advice, a possible solution is to rename the page name editar-empresas.php for empresas-editar.php and use the function indexOf():

(function () {
    var nav = document.getElementById('menu'),
        anchor = nav.getElementsByTagName('a'),
        current = window.location.href.split("?")[0];
    for (var i = 0; i < anchor.length; i++) {
        if (current.indexOf(anchor[i].toString().split(".")[0]) >= 0) {
            anchor[i].children[0].className = "active";
        }
    }
})();

Obs.: the function split() was used to disregard the extension .php (remembering that she only works with strings and so the method was used toString()).

  • And it worked that way?

  • @Andersoncarloswoss yes.

Browser other questions tagged

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