Anna_B
Anna_B

Reputation: 890

Toggle link background color

This is my code:

$("li").click(function() {
  $("li").removeClass("active");
  $(this).toggleClass("active");
})
.active {
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
</ul>

If you click one link twice, the background color should disappear. Unfortunately, it does not work.

Can somebody help me please? Would be very happy!

Love.

Upvotes: 1

Views: 25

Answers (2)

Bryan Dellinger
Bryan Dellinger

Reputation: 5294

add not this select to the li remove class

$("li").click(function() {
  $("li").not(this).removeClass("active");
  $(this).toggleClass("active");
})
.active {
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
</ul>

Upvotes: 0

charlietfl
charlietfl

Reputation: 171679

The problem is the first step removes the class on all <li> , including the current one if applicable. Then if it was already removed from current one toggLeClass() will add it back.

Simple fix is use not() for the removal and exclude the current <li>

$("li").click(function() {
  $("li").not(this).removeClass("active");
  $(this).toggleClass("active");
})
.active {
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
</ul>

Upvotes: 1

Related Questions