kawnah
kawnah

Reputation: 3414

Toggle classes between two different elements

I want to toggle between two classes on two anchor tags. When I click on the non-bold link, I want it to go bold, and then the other go to normal. However I don't really know how to go about it.

I've tried a few approaches:

$(".link").click(function(e) {
    e.preventDefault();
      if ($(this).hasClass("selected")) {
        $(this).removeClass("selected");
      } else {
        $(this).addClass("selected");
      }
  });
.selected {
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div class="two-links">
  <span>Filter By:</span>
  <a class="link selected" href="#">Link1</a>
  <a class="link" href="#">Link2<a>
</div>

Here, I add and remove based on the target and check if that class is present but it doesn't handle the other non-clicked anchor - I need to click that to remove the bolding when it needs to happen automatically.

I then mess around toggleClass():

 $(".link").click(function(e) {
    $(this).toggleClass("selected");
 });
.selected {
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
    <div class="two-links">
      <span>Filter By:</span>
      <a class="link selected" href="#">Link1</a>
      <a class="link" href="#">Link2</a>
    </div>

Which is definitely a step closer but I don't understand how to establish a relationship with toggleClass() and more than one element.

Am I going about this the right way or is there something better?

Upvotes: 0

Views: 70

Answers (3)

Huangism
Huangism

Reputation: 16438

A simpler solution

$(".link").click(function(e) {
    e.preventDefault();
    $(".link").removeClass("selected");
    $(this).addClass("selected");
});

Remove selected class from all .link then add it to the clicked element. This will work for more than 2 links and it is simpler. There is no need to check for selected class or get siblings.

Upvotes: 0

kawnah
kawnah

Reputation: 3414

The accepted answer is the right one, but something that should be added:

$(".link").click(function(e) {
    var isSelected = $(this).hasClass("selected");
    e.preventDefault();
    if (!isSelected) {
      $(this).toggleClass("selected");
      $(this).siblings('a').toggleClass('selected');
    }
});

Essentially, only perform the toggle action if what you're clicking on is NOT the selected element.

Upvotes: 0

Zvezdas1989
Zvezdas1989

Reputation: 1465

How about this. You can use siblings() method.

$(".link").click(function(e) {
    $(this).toggleClass("selected");
    $(this).siblings('a').toggleClass('selected');
});
.selected {
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div class="two-links">
  <span>Filter By:</span>
  <a class="link selected" href="#">Link1</a>
  <a class="link" href="#">Link2</a>
</div>

Upvotes: 1

Related Questions