Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add/remove active class for ul list with jquery?

Tags:

I'm trying to remove and set an active class for a list item every time it's clicked. It's currently removing the selected active class but isn't setting it. Any idea what I'm missing?

HTML

<ul class="nav nav-list">
  <li class='nav-header'>Test</li>
  <li class="active"><a href="page1.php">Page 1</a></li>
  <li><a href="page2.php">Page 2</a></li>
  <li><a href="page3.php">Page 3</li>
</ul>

jquery:

 $('.nav-list').click(function() {

    //console.log("Clicked");
    $('.nav-list li.active').removeClass('active');
    $(this).addClass('active');
});
like image 358
Paul Avatar asked Nov 24 '13 18:11

Paul


2 Answers

this will point to the <ul> selected by .nav-list. You can use delegation instead!

$('.nav-list').on('click', 'li', function() {
    $('.nav-list li.active').removeClass('active');
    $(this).addClass('active');
});
like image 113
Ry- Avatar answered Oct 08 '22 06:10

Ry-


you can use siblings and removeClass method

$('.nav-link li').click(function() {
    $(this).addClass('active').siblings().removeClass('active');
});
like image 37
Naitik Shah Avatar answered Oct 08 '22 04:10

Naitik Shah