Jon
Jon

Reputation: 8541

jQuery - Cannot Remove Class

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; }​

http://jsfiddle.net/Nvrp8/

Upvotes: 3

Views: 1252

Answers (4)

BZink
BZink

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?' );       
    });             
});​

http://jsfiddle.net/Nvrp8/8/

Upvotes: 4

Ryan Kinal
Ryan Kinal

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

Jeff Fabiny
Jeff Fabiny

Reputation: 325

It's working just fine, the listener is still bound. http://jsfiddle.net/Nvrp8/5/

Upvotes: 1

mittmemo
mittmemo

Reputation: 2090

You need to unbind the click listener.

http://jsfiddle.net/Nvrp8/2/

$(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

Related Questions