1

I've got some jQuery that I'm using to change a class of two elements. It works once, and the elements change class once, but I want it to work interchangeably. so when they click they click the 'deselected' button it assigns itself the 'selected' class, and the 2nd button changes to a 'deselected' class. Here's the jQuery:

$('.network_bar_deselected').on('click', function(){
    $('.network_bar_selected').removeClass('network_bar_selected').addClass('network_bar_deselected');
    $(this).removeClass('network_bar_deselected').addClass('network_bar_selected');
});

and the HTML is quite simple:

<a href="#"><div class="network_bar_selected"><h4>Network Updates</h4></div></a>
<a href="#"><div class="network_bar_deselected"><h4>Latest Tweets</h4></div></a>
Whirlwind990
  • 99
  • 2
  • 14

2 Answers2

3

Add the handler to both the classes

$('.network_bar_selected, .network_bar_deselected').on('click', function () {
    $('.network_bar_selected').removeClass('network_bar_selected').addClass('network_bar_deselected');
    $(this).removeClass('network_bar_deselected').addClass('network_bar_selected');
});

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
3

Since you're changing classes dynamically, you should use delegation:

$(document).on("click", ".network_bar_deselected", function() {
    $('.network_bar_selected').removeClass('network_bar_selected').addClass('network_bar_deselected');
    $(this).removeClass('network_bar_deselected').addClass('network_bar_selected');
});

Your original code only binds the handler to the elements with the network_bar_selected class when the document is loaded, not to elements that get that class later.

Barmar
  • 741,623
  • 53
  • 500
  • 612