-2

I am quite new here and to jQuery but I have searched the related questions in stackoverflow but none is solving my problem. I have this code:

Html:

<div class="menu">
    <div class="menu-items">
       <ul class="nav">
         <li class="var_nav">
            <a href="../home.php">Home</a>
         </li>
         <li class="var_nav">
            <a href="../portfolio.php">Porfolio</a>
         </li>
         <li class="var_nav">
            <a href="../dashboard.php">Dashboard</a>
         </li>
         <li class="var_nav">
            <a href="../users.php">Users</a>
         </li>
       </ul>
    </div>
</div>

CSS

.nav li.active {
    background-color: #048abb;
}
.nav li.active a {
    color: #fff;
}

I want to apply class .active to the clicked(current/active) link so that the css can take effect. Any suggestions on how to apply the class to obove html code via jQuery?

1

3 Answers 3

1
var $links = $('.nav a').on('click', function(e) {
    e.preventDefault();

    $links.removeClass('active');
    $(this).addClass('active');
});
Sign up to request clarification or add additional context in comments.

2 Comments

jmar777 The obove code renders the links unresponsive
@Zollo well, if you're planning on following the links, why would you mess with the classnames? If the links actually perform navigation, you'd want to set the classnames server-side.
0
$(document).ready(function(){
    $('.nav').on('click', 'a', function(e) {
        e.preventDefault();
        $('.active).removeClass('active');
        $(this).addClass('active');
    });
});

Comments

0

As the CSS seems to address the "active" class being applied to the LI elements, this should do the trick:

$(document).ready(function() {

    $('.nav a').click(function(e) {

    //optional - override the link - uncomment the following line:
    //e.preventDefault();

    //remove the active class from all li elements
    $('.nav li').removeClass('active');

    //add it to the li element holding the clicked link
    $(this).parent('li').addClass('active');

    });

});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.