So i have click function and i’m calling this function couple times on same div, so basicly i have this kind of div:
<div id="upload_submit" class="upload_submit">Content</div>
and i have two click functions:
//first function
$('.upload_submit').click(function(){
$(this).removeClass('upload_submit');
$(this).addClass('upload_cancel');
});
//second one
$(".upload_cancel").click(function(){
alert('test')
});
So by default my div have class upload_submit after i click on that div i change class to upload_cancel so now if i click again i should get alert but for some reason it doesn’t happen, what could be wrong?
.bind()(which .click is a wrapper around) only binds to elements existing at the time of the call. But you are dynamically changing the class meaning that there is no.upload_cancelto bind to when you try to bind it. Therefore you need adelegated event:Or if you are using 1.7+ you can use the
.on()syntax:What this will do instead is bind a handler to the
documentelement for a click event. It will then check if the triggering element matches your selector you passed in, if it does it will call your handler. This means that you can add and remove elements matching the selector provided and it will still call your click event handler correctly since the event is bound to thedocumentnot your specific element.Here is a jsFiddle example of this solution.
For more information you can start reading this article.