Reputation: 69
I have a link that, If I click on it while is set with .m
the class changes to .n
, But if I click on it again, once It is supossed to have changed, it doesnt show up the alert...what is wrong?
HTML
<div class="m" >[enlace]</div>
JQUERY
$(".m").on('click',function(){
$(this).addClass("n");
$(this).removeClass("m"); //or toggleClass?
});
$(".n").on('click',function(){
Alert("n");
});
It looks like it doesnt recognize the div have a new .n
class that the alert doesnt show up.
Upvotes: 1
Views: 70
Reputation: 11
You'll need to attach events on dynamic elements in Jquery like the one below:
$(document).on('click', '.m', function() {
$(this).addClass('n');
$(this).removeClass('m');
});
$(document).on('click', '.n', function() {
alert("n");
// $(this).addClass('m');
// $(this).removeClass('n');
});
Jquery will not be able to attach an event on a dynamic element on page load. Since the element with class 'n' will not be available until the element with class 'm' is clicked the selector $('.n') will not return anything. So we attach a click event to the Static 'document' element and indicate the future element i.e., $('.n') inside it to invoke the event.
Upvotes: 0
Reputation: 911
So you can do it this way:
$(".clickable").on('click',function(){
if ($this).hasClass("m")) {
$(this).addClass("n");
$(this).removeClass("m"); //or toggleClass?
} else {
alert("n");
}
});
Upvotes: 2
Reputation: 1106
I can't explain you why it does this. But if the event click on ".m" is still listening when '.m' is no more there, you can just use a count like this :
$(document).ready(function(){
var count = 0;
$('.m').on('click', function(){
if(count == 0){
$(this).toggleClass('n');
$(this).toggleClass('m');
count++;
}else{
alert('OK');
}
});
});
Upvotes: 0