Using jQuery.on () event handler for dynamically loaded image
My pages are generated dynamically with ajax response.
Each answer has an element img
with the specified id. I need them to disappear on boot.
.load()
and .bind('load')
works great when the page is loaded for the first time. But doesn't work in the following answer for sure.
$('#my_img').load(function(){
$(this).hide().fadeIn('slow');
});
So I need to use an event handler .on()
. But it doesn't work.
$('body').on('load','#my_img',function(){
$(this).hide().fadeIn('slow');
});
Note. This is not a cache issue. Img src also has a random query string.
source to share
onload
the event does not bubble, so you cannot delegate it. But, if you don't need to support IE8 <, you can capture the event instead, which will work for any dynamic img:
document.body.addEventListener(
'load',
function(event){
var elm = event.target;
if( elm.id === 'my_img'){ // or any other filtering condition
// do some stuff
}
},
true // Capture event
);
-DEMO -
source to share
You can try using Jquery's ready event rather than on.load to run some code when the element is ready.
Here's a fiddle I made to demonstrate it in action: https://jsfiddle.net/yosefh/66g0xjre/1/
$(document).ready(function() {
$('div').click(function() {
var newDiv = $('<div></div>');
$(newDiv).ready(function() {
$(newDiv).fadeIn("slow");
});
$('body').append(newDiv);
});
});
source to share