DanFromGermany DanFromGermany - 1 month ago 4
Ajax Question

Apply code to dynamically loaded image

I have a page where an image with a wrapping div gets loaded via ajax. I need to apply some code when that image is loaded. I cannot alter the ajax call so I cannot simply use

on the ajax call.
After some time the image with the div gets reloaded the same way (it is a kind of rotation).

The structure is like this:

<div id="spot">
<div id="xyz">
<a href="http://someurl.com">
<img src="http://someimage.url" />

The "spot" div is fixed and everything inside of it gets loaded dynamically.

When I put in

$('#xyz img').on('load', myCallback);

It doesn't work, I think because when the image gets reloaded, the listener is also removed.

I tried with the delegated listener:

$('#spot').on('load', '#xyz img', myCallback);

but didn't work either, it doesn't get executed (I've put console.log inside to verify what happens).

When I type in console
$('#spot #xyz > img')
the console shows the correct object.

How can I run my
function right after the dynamic content with the image is ready for some DOM scripting action?


If you can't get access to the AJAX request callback then your options are limited to a setInterval() timer which checks to see if the elements have been added, a MutationObserver or a load event on an img element - but be aware this will only fire after the src of the image has loaded so there will be a delay.

Here's how you can use the MutationObserver, but be aware this will only work for newer browsers:

var targetElement = document.querySelector('#container');
var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        // perform the required actions here...

observer.observe(targetElement, { attributes: true, childList: true, characterData: true });