lukas.pukenis
lukas.pukenis

Reputation: 13597

jQuery 1.7.1 on() not working while live() works

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

Answers (3)

thecodeparadox
thecodeparadox

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

T.J. Crowder
T.J. Crowder

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

Royi Namir
Royi Namir

Reputation: 148524

the main selector should be on a WRAPPER ELEMENT

$('#MyWrapperElement').on('click',".box_tile_image",function() {
console.log('click');   
});

Upvotes: 5

Related Questions