Home > Back-end >  jQuery toggle & remove class not correct
jQuery toggle & remove class not correct

Time:08-14

I have simple jQuery toggle class and remove class.

Assume I have 5 menu. Now when I click one menu then the arrow will set to down position.

Then now try to click another menu, the arrow down from previous menu is not back from the original position.

What I need is when I click one menu then click another menu then another arrow should back to the original position.

for(var i=0; i<5; i  ) {
  var el = "<div class='click' style='padding: 10px; cursor: pointer;'><i class='fa-regular fa-angle-right'></i></div>";
  
  $(".menu").append(el);
}

$(".click").click(function(e) {
  $(".menu").removeClass("expanded");
    $(this).find("i").toggleClass("expanded");
});
.expanded {
  transform: rotate(90deg);
  opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://site-assets.fontawesome.com/releases/v6.1.2/css/all.css">

<div ></div>

CodePudding user response:

One solution is removeClass from all i elements except the clicked one by not method.

$(".click i").not(iEle).removeClass("expanded");

Before toggleClass for clicked one.

for(var i=0; i<5; i  ) {
  var el = "<div class='click' style='padding: 10px; cursor: pointer;'><i class='fa-regular fa-angle-right'></i></div>";
  
  $(".menu").append(el);
}

$(".click").click(function(e) {
  const iEle = $(this).find("i");
  $(".click i").not(iEle).removeClass("expanded");
  iEle.toggleClass("expanded");
});
.expanded {
  transform: rotate(90deg);
  opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://site-assets.fontawesome.com/releases/v6.1.2/css/all.css">

<div ></div>

  • Related