Reputation: 165
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");
})
Upvotes: 4
Views: 26
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