Reputation: 5933
I have following code in document.ready()
as :
$(document).ready(function(){
$('img').addClass('myClass');
});
Now this code works fine if I loads all the images at once, then this function adds the myClass to them(all img's).
But what happens here is that whenever a new element with tag img like <img...../>
is added in the DOM (via ajax or javascript), class to it does not gets added.. is it a limitation of JQuery or it provides this via some plugin or api,or we have to do it manually.
I want whenever a new img is added in DOM its class would set to myClass,
PS Right now I used setTimeout() like this to call a function after 2 secs to add classes to my images as :
setTimeout(function(){
$('img').addClass('actAsButton');
},2000);
But is this the right way of doing, in fact this code also fails if we adds any new in DOM after 2 secs for that to happen I can use setInterval instead but that is quite costly in terms of memory usage.Please shed some light..
Upvotes: 1
Views: 79
Reputation: 68
In your case the addClass
is not working because the img element was not there when $(document).ready()
was fired. S0, you should use following code for that.
$('img').live('load', function () {
$('img').addClass('actAsButton');
});
Upvotes: 0
Reputation: 2264
$(document).on('img', 'load', function() {
$(this).addClass('actAsButton');
});
Upvotes: 0
Reputation: 87073
$('img').load(function() {
$(this).addClass('actAsButton');
})
Upvotes: 1