Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
HTML
<ul class="main-menu" id="main-menu">
        <li class="main-menu__item active" ui-sref="home">
            <a href="">
                <div class="title">DASHBOARD</div>
            </a>
        </li>

        <li class="main-menu__item" ui-sref="settings">
            <a href="">
                <div class="title">CONFIGURACIÓN</div>
            </a>
        </li>
</ul>

<pre lang="CSS">
.main-menu__item a {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    height: 55px;
    padding-left: 20px;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    border-bottom: 1px solid #eaeaea;
    cursor: pointer;
}
.main-menu__item.active a .title {
    color: #f49e00;
}


What I have tried:

$('li.main-menu__item').click(function(){
    $('li.main-menu__item').removeClass("active");
    $(this).addClass(" active");
});


It is working fine but only when i click second time to the same menuitem, first time when i clicks on the link, active class is added but only for second.
is there any other way to solve this using angularjs or jquery? please suggest.
thanks in adv.
Posted
Updated 31-May-18 5:58am

1 solution

If you want to stay on the same page and update the class of the clicked item, then you need to prevent the browser from following the hyperlink:
JavaScript
$('li.main-menu__item').click(function(e){
    $('li.main-menu__item').removeClass("active");
    $(this).addClass(" active");
    e.preventDefault();
});
Demo[^]

If you want to follow the hyperlink to load a new page, then you'll need to change the active item in the HTML you return from the new page. Either edit the static HTML page, or use server-side code to generate the menu.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900