user3135757
user3135757

Reputation: 165

issues in event response

I can't understand why Test keep on firing even though the class open has been added to it ? any idea on how to make it in the right way so it will stop on firing when open class is added?

<div class="changer">Test</div>
$(".changer:not('open')").on("click",function(){
        $(this).addClass("open");
        alert("passed");
    })

http://jsfiddle.net/ng2guchg/

Upvotes: 4

Views: 26

Answers (1)

adeneo
adeneo

Reputation: 318232

It's because the elements are gotten when the page loads, and the event handler is attached at that moment, changing the class later doesn't remove the event handler.

The solution is to either check for the class inside the event handler

$(".changer").on("click", function(){
    if ( ! $(this).hasClass('open') ) {
        $(this).addClass("open");
        alert("passed");
    }
});

or to make the event handler fire only once, you could use jQuery one() if it fits your needs.

Upvotes: 5

Related Questions