Reputation: 399
why my alert does not work?
$('.checkprice').click(function(el){
$(this).addClass('checkcheck');
});
$( '.checkcheck' ).on( "click", function() {
alert('yes');
});
May be .checkcheck creates more longer, than .on() start?
Waht I must to do?
Upvotes: 0
Views: 65
Reputation: 59
As Robin mentioned, try something similar to
var checked = false;
$('.checkprice').click(function(){
$(this).addClass('checkcheck');
$(this).click(function(){
if ( checked == false ) {
alert('yes');
checked = true;
}
});
});
I was also unaware of the one()
event which is fancy, and rids the need for checking a variable and firing off multiple redundant events.
$('.checkprice').click(function(){
$(this).addClass('checkcheck');
$(this).one('click', function(){
alert('yes');
});
});
If you need the check to only fire once then one()
could be used on both events.
$('.checkprice').one('click.checkprice', function(){
$(this).addClass('checkcheck');
$(this).one('click', function(){
alert('yes');
});
});
You can also use on()
delegation on the body as Jonathan mentioned
var checked = false;
$('body').on('click', '.checkprice', function(){
$(this).addClass('checkcheck');
});
$('body').on('click', '.checkcheck', function() {
alert('yes');
checked = true;
});
Upvotes: 0
Reputation: 268334
jQuery will setup event handlers immediately on all matched elements. For instance, the following code will apply to any element that has .checkcheck
as a class only at the time the code is ran, and not at some future time:
$( ".checkcheck" ).on( "click", handleCheck );
If that class is added to an element at a future time, this handler will not handle click events for it, since it didn't have the class at the time $.fn.on
was called originally.
The most popular way around this issue is to leverage Event Delegation, which utilizes the bubbling-nature of JavaScript events. Rather than placing a handler directly on all .checkcheck
elements, we can place one further up the DOM tree:
$( document ).on( "click", ".checkcheck", handleCheck );
Now we don't care if an element has .checkcheck
as a class when this script is ran, we only care if it has that class when the event bubbles up to the document. This means we can add brand new elements to the DOM, given them the .checkcheck
class, and they will trigger handleCheck
when clicked.
Upvotes: 1