Reputation: 691
I'm using this lazy load jQuery script ( http://www.appelsiini.net/projects/lazyload ) to lazy load images when they appear in the viewport, but I want to run some javascript / styling to style the new, full image that is loaded.
How can I run javascript once the image has been loaded?
Upvotes: 1
Views: 1033
Reputation: 13221
The jQuery Lazy Load plugin has a callback parameter called appear, that gets triggered for every image, once it's been loaded. Use it like this, in this case e.g. to put a red border on the image, once it's loaded (this in the callback refers the raw DOM img object):
$(document).ready(function () {
$("img").lazyload({
appear: function () {
//Image is loaded. Put javascript here.
this.style = "border: 1px solid red";
}
});
});
Although I will say, if you wanna add styling to the image, you should use css instead. But there might be cases where you actually wanna trigger javascript on image-load, and this seems like the way to do it with the lazy load plugin :)
Upvotes: 1
Reputation: 18292
Bind a handler to the image load event. But be aware that you have to set the handler fore every image, as the load
event doesn't bubble up the DOM tree. Here is a way:
$('#img').on('load', function() {
//do some styling...
});
However, my experience tells me that, with this event it's better if you use the onclick
attribute. It my happen that, when you set the handler via jQuery, some images have already loaded.
Upvotes: 1