Reputation: 13597
I have a simple code snippet
$('.box_tile_image').live('click', function() {
console.log('click');
});
The problem is I want to use on()
as live()
is deprecated, however if I use on in the case above - I do not get "click", while if I replace on with live it works like a breeze.
What can be the problem?
Upvotes: 1
Views: 684
Reputation: 87073
$(document).on('click', '.box_tile_image', function() {
console.log('click');
});
or you can use delegate()
$(document).delegate('.box_tile_image', 'click', function() {
console.log('click');
});
Instead of document
you can also use any ancestor of box_title_image
.
Suppose if you have DOM like follwing:
<div id="container">
<img class="box_tile_image" src="" alt="">
</div>
Then you can write:
$('#container').on('click', '.box_tile_image', function() {
console.log('click');
});
or
$('#container').delegate('.box_tile_image', 'click', function() {
console.log('click');
});
Upvotes: 1
Reputation: 1074198
The equivalent would be:
$(document).on('click', '.box_tile_image', function() {
console.log('click');
});
...and in fact, if you look at the jQuery source from 1.7 onward, that's all live
is.
Now, that said, I'd strongly recommend hooking the click on something closer to the target elements, rather than all the way up at the document
. But for a literal equivalent, if the elements in question really have no other common ancestor, that's what you would do.
Upvotes: 5
Reputation: 148524
the main selector should be on a WRAPPER ELEMENT
$('#MyWrapperElement').on('click',".box_tile_image",function() {
console.log('click');
});
Upvotes: 5