15

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

d-_-b
  • 21,536
  • 40
  • 150
  • 256

2 Answers2

38

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(){ });
Johan
  • 35,120
  • 54
  • 178
  • 293
  • 1
    Thanks, what if `#container` is the same element as `.element` ? I've tried using the same element in both places, but no luck :/ – d-_-b Feb 26 '13 at 15:17
  • 2
    @iight Then it wont work. `#container` cant be dynamically generated. As j08691 said, pick a wrapping element as close to the dynamically added element as possible to improve performance. – Johan Feb 26 '13 at 15:19
  • must be a parent element, though, right? – d-_-b Feb 26 '13 at 15:20
  • 1
    @iight Correct. A parent element which is not dynamically generated, and as close as possible in the DOM. – Johan Feb 26 '13 at 15:20
  • 1
    @iight Np, glad to help! – Johan Feb 26 '13 at 15:22
  • FYI Inside the function, $(this) will be equal to $('.element'), not $('#container') – toad May 10 '16 at 18:43
10

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.

j08691
  • 204,283
  • 31
  • 260
  • 272
  • 1
    Thanks! this works, but now I just have to research the whole $(document) binding. This does fix the issue though! – d-_-b Feb 26 '13 at 15:17