Reputation: 8541
I cannot seem to remove the class 'foo' and I do not understand why. When the user clicks on .foo jQuery is suppose to remove .foo. At first glance it seems to work as the text is no longer red. However, clicking .foo several times will result in the alert box appearing thus meaning .foo has not completely been removed. I do not understand why this is happening.
jQuery:
$(document).ready(function() {
$('.foo').click(function() {
$(this).removeClass('foo');
alert('Class .foo should have been removed. Why is this alert still appearing?');
});
});
html:
<p class="foo">foo</p>
css:
.foo { color: red; }
Upvotes: 3
Views: 1252
Reputation: 7967
If you use on() it actually evaluates the selector for each click because the event is bound to body, not to ".foo"
$(document).ready(function() {
$("body").on("click", ".foo",function() {
$(this).removeClass('foo');
alert( 'Class .foo should have been removed. Why is this alert still appearing?' );
});
});
Upvotes: 4
Reputation: 17732
When you run $('.foo')
, you get a static set of elements that have class="foo"
at that time. So, even if you removeClass('foo')
from those elements at a later time, you still bound the listener to that original set of elements.
If you want to change that behavior, consider looking at .on
or .delegate
.
Upvotes: 3
Reputation: 325
It's working just fine, the listener is still bound. http://jsfiddle.net/Nvrp8/5/
Upvotes: 1
Reputation: 2090
You need to unbind the click listener.
$(document).ready(function() {
$('.foo').click(function() {
$(this).removeClass('foo');
alert( 'Class .foo should have been removed. Why is this alert still appearing?' );
$(this).unbind('click');
});
});
Upvotes: 5