Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Cannot Remove Class

Tags:

jquery

css

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/

like image 233
Jon Avatar asked Aug 07 '26 12:08

Jon


2 Answers

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');        
    });             
});​
like image 63
mittmemo Avatar answered Aug 09 '26 03:08

mittmemo


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/

like image 24
BZink Avatar answered Aug 09 '26 04:08

BZink



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!