Select menu when clicking

Asked

Viewed 102 times

1

I would like to create a javascript function that when the user clicks on some menu item it gets active, I did some research on the internet but could not play in my code.

<nav class="site-menu">
<ul id="nav">
    <li >
        <a asp-controller="Home" asp-action="Index" onclick="mostrarAtivo"><span>Home</span></a>
    </li>
    <li >
        <a  asp-controller="QuemSomos" asp-action="Index" onclick="mostrarAtivo"><span>Quem Somos</span></a>
    </li>

    <li onclick="mostrarAtivo">
        <a><span>Lançamentos</span></a>
        <ul class="sub-menu">
            <li><a asp-controller="Imoveis" asp-action="Casas">Casas</a></li>
            <li><a asp-controller="Imoveis" asp-action="Apartamentos">Apartamentos</a></li>
            <li><a asp-controller="Imoveis" asp-action="SalasComercial">Salas Comerciais</a></li>

        </ul>
    </li>

    <li onclick="mostrarAtivo">
        <a><span>Imóveis</span></a>
        <ul class="sub-menu">
            <li><a asp-controller="Imoveis" asp-action="Alugar">Alugar</a></li>
            <li><a asp-controller="Imoveis" asp-action="Comprar">Comprar</a></li>
        </ul>
    </li>

    <li>
        <a asp-controller="CadastroImovel" asp-action="Proprietario"><span>Cadastre seu imóvel</span></a>
    </li>
    <li>
        <a href="components/accordion.html"><span>Contato</span></a>
    </li>
</ul>
</nav>

js:

<script>
    function setActive() {
        aObj = document.getElementById('li').getElementsByTagName('a');
        for (i = 0; i < aObj.length; i++) {
            if (document.location.href.indexOf(aObj[i].href) >= 0) {
                aObj[i].className = 'active';
            }
        }
    }
</script>

Basically it is the user to click and activate the bootstrap active

1 answer

2


Opa Amigo, Using jquery da to do as follows:

$('a').on('click',function(){
    $(this).toggleClass('active')
})

takes all elements a using the $('a') selector and adds a click reader for each of them.

then add this, saying that the clicked element will receive the active class.

toggle does that whenever clicked on the element it adds or removes the class.

I hope I’ve helped.

Browser other questions tagged

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