Reputation: 166
I am loading html data via ajax, containing images, into a div on my page using
$('#container').html(data)
assuming that the variable data is what the ajax returned, how can i know when the new data (and images) finished loading in the container?
Upvotes: 1
Views: 58
Reputation: 4774
What you are looking for is .promise().done()
. These are also useful in situations like when you want to wait for any and all animations running on a collection or jQuery object to finish, without passing your code in individual callbacks.
If what you are looking to do is call code or a handler on content that is loaded then you should look at the .load()
event and delegated event handlers. You may not need both, but you should read, know, and understand them anyway. You can read about delegated event handlers in the docs for the .on()
method.
Quick Summary of Delegated Event Handlers
Delegated event handlers are handlers that you attach to an ancestor element of the content (which may or may not have been loaded yet) that you want to listen on.
The following is an example of a delegated click
handler being bound to the body
element and set to listen for a click
event on a descendant element with class foo
. This means this handler will listen to any and every element with class foo
(even those that are added later and not yet loaded into the DOM) that is a descendant of the body
element.
$("body").on("click", ".foo", function() {
bar();
});
The below does exactly the same thing, except that it only binds the handler to those .foo
elements that exist at the time the handler is bound. The handler will not listen to any .foo
elements added later.
$(".foo").on("click", function () {
bar();
});
By passing the a selector argument to the .on()
method, you can tell jQuery that rather than listen for the specified event to happen on the bound element, it should instead listen for a propagated (or bubbled) event that originated from a descendant matching the given selector to reach the bound element, and should call the handler using the descendant that triggered the event as the the context object (this
) for the handler.
Relevant Links to jQuery's API
Upvotes: 2