Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) ?

like image 907
d-_-b Avatar asked Feb 26 '13 15:02

d-_-b


2 Answers

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(){ });
like image 77
Johan Avatar answered Oct 02 '22 14:10

Johan


You should be able to use a format like this:

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

Where element is the element you want to bind the click event to. Using document is kind of a worst-case scenario since you ideally want to use an element that exists when the DOM is loaded that is closer in the DOM hierarchy to the element that will be dynamically loaded.

From the jQuery .on() docs:

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.

like image 43
j08691 Avatar answered Oct 02 '22 14:10

j08691