jQuery('.unclicked').on('click',function(e){
nClicks = nClicks+1;
jQuery(this).removeClass('unclicked');
jQuery(this).off('click');
e.preventDefault();
alert("CLICK ON UNCLICKED ELEMENT, Elements Clicked" + nClicks);
});
Use .on()
instead of .click()
, then you can use .off()
to unbind the handler.
The reason your problem was occurring is because even though you were removing the unclicked
class, the elements themselves had event handlers bound to them that will stay bound regardless of changes to the elements structure.
Another way you could accomplish this without having to unbind each handler as you go, is delegate the event to the nearest static parent element.
jQuery('#parent').on('click', '.unclicked', function(e){
// Your code
// Remove .unclicked class
});
This would work because the handler gets evaluated when the event bubbles up to the #parent
, which would check each time if the element matches the condition (which in the above case is that it has the class .unclicked
)