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) ?
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(){ });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With