0

I have new articles that are loaded dynamically with ajax and I want to perform something on them when their image is loaded.

All the articles are in a div called #tracks, so this is how I access to the image of the articles: '#tracks article div'.

Everytime there are new posts loaded using ajax, as well as the first time we load the page, I want to call a function.

$('#tracks').on('load', 'article img', function() {blabla})

I tried doing this, but it doesn't work because the load event can only be called on elements associated to an url. But the event is called on every image as you can see (wich are related to an url), but because the parent is #tracks (div that is not associated to an url), it does not seem to work (this event never gets triggered).

I also tried this:

$(window).on('load', '#tracks article img', function() {blabla})

But window does not seem to be a parent to my #tracks div. The event does not get triggered when new articles (that contains an image) are loaded.

How can I make this work?

0

2 Answers 2

2

How can I make this work?

You can't. The load event does not bubble and hence event delegation cannot be used. From the .on documentation (emphasis mine):

In all browsers, the load, scroll, and error events (e.g., on an <img> element) do not bubble. In Internet Explorer 8 and lower, the paste and reset events do not bubble. Such events are not supported for use with delegation, but they can be used when the event handler is directly attached to the element generating the event.


All you can do is bind the event handler directly to the elements whenever you add them to the document (e.g. in your Ajax success handler).

2
  • Thank you, but I do not understand this: but they can be used when the event handler is directly attached to the element generating the event. Do you have an example?
    – user1834464
    Commented Jul 17, 2013 at 16:55
  • Just normal event handler binding: $('#tracks article img').on('load', ...). You probably want to filter the selection to only include the image elements that have just been added. Commented Jul 17, 2013 at 16:56
0

you can do a simple thing to Make this work.

after you AJAX call is complete successfully completed use $.trigger to trigger a custom event which is simply a string. then listen for it on the parent or any ancestor element.

1
  • But you cannot be sure that the images are really loaded at the time you trigger the event. Commented Jul 17, 2013 at 16:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.