Reputation: 99
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>
Upvotes: 1
Views: 1435
Reputation: 782785
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.
Upvotes: 3
Reputation: 388446
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
Upvotes: 3