Could someone please help me to understand the difference between these two jQuery functions?
$('#theElement').click(function() {
... click handler code ...
});
AND
$('body').on('click', '#theElement', function() {
.... click handler code ...
});
According to jQuery's documentation, .click()
is just a shortcut for .on('click')
. And that's the way I've always found it to work. However, I noticed a key difference when building out a prototype today. I could not use .click()
when trying to assign an even listener to an element that wasn't yet in the DOM. However, if I did it with $('body').on('click', '#theElement'...
, it worked!
Trying to understand why...
Does the .on()
have something to do with event capturing that .click()
does not?
Thank you to whoever can help point me in the right direction. This is driving me nuts!
.click()
is a shortcut for.on("click", handler)
. So that's the signature you need to look at in the.on()
docs.on()
API