the active class is not deleted when another button is clicked.

<ul class="nav nav-tabs text-center" id="cTabs" > <li><a href="/" class="active">bütün mallar</a></li> <?php foreach ($categories as $categoryItem): ?> <li > <a href="/category/<?php echo $categoryItem['id']; ?>" class="" > <?php echo $categoryItem['name']; ?> </a> </li> <?php endforeach; ?> </ul> 

here is the script:

  $("#cTabs li a").click(function(){ $("#cTabs li a .active").removeClass("active"); $(this).addClass("active"); }); 
  • because the handler is on li , and you click, most likely, on a ...... by the way, in the end, you also add an active to li - Aleksey Shimansky
  • No, this typo was corrected - Tofiq Şamedov
  • one
    then again review the code ....... a .active ....... the space does not confuse? Although there generally should just be $("#cTabs li a").removeClass("active"); Just in case, to remove the activity from all - Alexey Shimansky
  • all the same, no, he sort of clears up for a second first, then again throws over the 1st element - Tofiq Şamedov
  • it's not even about removing, but the fact that it does not add a class to another element - Tofiq Şamedov

2 answers 2

 $("#cTabs li a").click(function(e) { e.preventDefault(); $("#cTabs li a").removeClass("active"); $(this).addClass("active"); }); 
 ul.nav li a.active { color: #f00; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="nav nav-tabs text-center" id="cTabs"> <li><a href="/" class="active">bütün mallar</a></li> <li><a href="/category/1" class="">1</a></li> <li><a href="/category/2" class="">2</a></li> <li><a href="/category/3" class="">3</a></li> <li><a href="/category/4" class="">4</a></li> </ul> 

  • Cheg, now the buttons work, but there are no links - Tofiq Şamedov
 $("#cTabs li a .active").removeClass("active"); 
 $("#cTabs li a.active").removeClass("active"); // ^--- тут нет пробела 
  • he still preventDefault not preventDefault - Alexey Shimansky
  • I did e preventDefault, the buttons are switched, but the links do not go - Tofiq Şamedov
  • got it? the links now do not go. Broken! - Igor
  • @ TofiqŞamedov - Choose one thing: either you change the properties of the DOM elements and stay on the same page, or you load another page and set the class to the active element during the page generation / loading. - Igor
  • I see, thanks - Tofiq Şamedov