Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect image load by jQuery

<img src="http://site.com/image.png" />

I change src of this image on .click event.

There can be loaded more than 20 different images, after changing src.

1) How do I know, was image already loaded (should be cached) or it has to be loaded?

2) How to run two different functions, for loaded and not?

Thanks.

like image 274
James Avatar asked Mar 13 '11 22:03

James


People also ask

How check image is loaded or not in jQuery?

To check if an image is loaded successful or not, you can combine the use of jQuery 'load()' and 'error()' event : $('#image1') . load(function(){ $('#result1'). text('Image is loaded!

How can I check image load?

To determine whether an image has been completely loaded, you can use the HTMLImageElement interface's complete attribute. It returns true if the image has completely loaded and false otherwise. We can use this with naturalWidth or naturalHeight properties, which would return 0 when the image failed to load.

How can add image in HTML using jQuery?

With jQuery, you can dynamically create a new image element and append it at the end of the DOM container using the . append() method. This is demonstrated below: jQuery.


1 Answers

You need to attach an event handler for the load event:

Update 2017:

$('img').on('load', function() {
    alert('new image loaded: ' + this.src);
});

Plain JS/DOM:

imgNode.onload = () => {
    alert('new image loaded: ' + this.src);
};
like image 126
jAndy Avatar answered Sep 30 '22 14:09

jAndy