I have a simple page that loads content dynamically.
I use the jQuery load function to append content to a div. The load function loads content from another file.
The problem I am having is that after the content loads, the jQuery functions I have built are not responding to click events.
To prove that it works otherwise, I include the content and after DOM loads it works perfectly. Need help please.
When you do something like this:
…only elements that are already in the DOM will be matched by the selector and have their click event hooked up; if you add elements later that would have matched the selector, they will not be automatically hooked up after-the-fact.
You can use event delegation to seemingly hook them up automatically using
delegateor (with newer versions of jQuery) one of theonvariants:(Note that the order of arguments is slightly different between the two.)
With event delegation, what really happens is that jQuery hooks
clickon the container, and when the click bubbles up to the container, it checks the path the event took to see if any of the elements in-between matched the selector. If so, it fires the handler as though you’d hooked it to the element, even though it’s actually hooked on the container.Concrete example:
If we do this:
…then clicking one of the spans will show its contents, and if we do this:
…that span will get handled automatically, because the event handler is on the container and then the selector checked when the event occurs, so it doesn’t matter that we added the element later.