I wrote jQuery event handlers on DOM elements that are not yet in the page but might be loaded asynchronously into the page. What I observed was these event handlers seem to not recognize that some new elements were added to the DOM and that they need to act on them on triggering.
Am I right in my observation? How do I achieve this functionality?
If you want event handlers to work on dynamically added content, you need to use
on
Of course this will cause all clicks anywhere on your page to be watched. To be more efficient, see if you can structure your page so that all of these elements whose
click
event you want to handle will be in one container. ie, if all of these elements are going to be added to a div with an id offoo
, you'd write the above more efficiently asIf you're using jQuery < 1.7, you'd use delegate
Yes.
Using the
.on
function to subscribe to those event handlers if you are using jQuery 1.7+:or using the
.delegate
function if you are using an older version (higher than 1.4.3):For both you could use a more specific root than
document
to improve performance if you know that those elements will be added to some container for example.And if you are using some prehistoric version you could go with
.live()
: