I need to add and remove 2 different classes to different elements with one click.-jQuery

Viewed 89

I want to add and remove a new class(Not toggle) in this span(footer-text)tag By clicking this div(footer-icon)tag. By jQuery or javascript. It needs to be work like siblings cause I have more span tag

For example-

<div class="footer-icon">Hello</div>

<span class="footer-text">Home</span>

Basically, I need to add and remove 2 different classes to different elements with one click. I need to click on this footer-icon class

Html-

  <svg version="1.1" class="footer-icon" viewBox="0 0 90 100" 
    xmlns="http://www.w3.org/2000/svg">
  </svg>
  <span class="footer-text">Home</span>

css-

.footer-icon-active{
    stroke: #fc494d;
}
.footer-active {
    color: #fc494d;
}

I have tried but it needs individual clicks

$(".footer-icon").click(function(event){
        $(".footer-icon").removeClass('footer-icon-active');
        $(this).addClass('footer-icon-active');
    });
    $(".footer-text").click(function(event){
        $(".footer-text").removeClass('footer-active');
        $(this).addClass('footer-active');
    });

enter image description here

1 Answers

So you have many .footer-icon and .footer-text pairs... And you want to set them as active on click of one of the other...

Try this:

// One click handler for both classes
$(".footer-icon, .footer-text").click(function(event){
  // Remove the two active classes everywhere
  $(".footer-icon").removeClass('footer-icon-active');
  $(".footer-text").removeClass('footer-active');
  
  // Depending which element was clicked
  // Add the active class to $(this)
  // and its corresponding prev or next sibling
  if($(this).is(".footer-icon")){
    $(this).addClass('footer-icon-active');
    $(this).next(".footer-text").addClass('footer-active')
  }else{
    $(this).prev(".footer-icon").addClass('footer-icon-active');
    $(this).addClass('footer-active')
  }
});
Related