on() vs live() click function on element that doesn't exist yet

d-_-b picture d-_-b · Feb 26, 2013 · Viewed 13k times · Source

As far as I know, the click() method isn't working for me because the element I'm clicking does not exist on page load (DOM ready).

I've found many answers suggesting to use .live('click',function(){...}). This works great!

However, .live() is depreciated as of jQuery 1.7

So, I've tried using .on('click',function(){...}) instead, but it doesn't not work (acts the same as .click().

Does anyone know why, or what I can do to use .on() similarly to .live() (which works) ?

Answer

Johan picture Johan · Feb 26, 2013

Since on() replaces both bind() and live(), you need to pass a third parameter in order to make use of event delegation (in other words, to make it work like the old live()):

$('#container').on('click', '.element', function(){ });