Reputation: 142
$('.option').click(function(){
$(this).addClass('selected');
});
$('.selected').click(function(){
$(this).removeClass('selected');
});
Trying to remove selected class when i click element which has class (selected).
addClas works, but remove does not. :/
Upvotes: 1
Views: 72
Reputation: 26320
You can use toggleClass
.
$('body').on('click', '.option', function() {
$(this).toggleClass('selected');
});
Upvotes: 4
Reputation: 31
$('.option').on('click', function(){
if(!$(this).hasClass("selected")) {
$(this).addClass('selected');
}
});
$('.selected').on('click', function(){
$(this).removeClass('selected');
});
But you'll get the best using toggle class method!
Upvotes: 1
Reputation: 2417
Your problem is you're attaching an event to an element that isn't ready to receive that event. You should attach the event to a parent element, then you can filter for the .selected
. This way it doesn't matter when your click able element gets added, it will work. This is called event delegation. You're delegating the task of handling the event to another element.
Your JS:
$(document).on("click", ".selected", function() {
$(this).removeClass('selected');
});
$(document).on("click", ".option", function() {
$(this).addClass('selected');
});
If you don't need different functionality on the individual buttons (which I assume you will) you can combine the two into this:
$(document).on('click','.selected.option',(function() {
$(this).toggleClass('selected');
});
Also when doing this, don't attach it to a parent that's too high up the tree. You want to attach it to the nearest possible parent element. We don't need to have a click event on something like document
because it's a good idea to be specific of which elements will get this event. Attaching it to document
will mean that any element, that has the class of .selected
, will be click able and respond to the same code. If you want to have different functionality in different buttons, you can't, because they're all responding to the same code attached to document
.
Upvotes: 3