Javascript / jQuery: How to detect img fully loaded or not?

All I have to do is find the image in the center of its parent div.
First off, I tried this.

$(document).ready(function() { $('#image1').css({ 'top': 50%, 'left': 50%, 'margin-top': (-$('#image1').height()/2) + 'px', 'margin-left': (-$('#image1').width()/2) + 'px' }); }); 

Failed to call $ ('# image1'). height () and width () give 0 before they are fully loaded.
Therefore, I tried to keep track of the size of the image until it had a certain width and height.
as,

 function inspectSize() { return ($('#image1').width() != 0); } function setPosition() { if(!inspectSize()) { setTimeout(setPosition, 1000); return; } $('#image1').css({ 'top': 50%, 'left': 50%, 'margin-top': (-$('#image1').height()/2) + 'px', 'margin-left': (-$('#image1').width()/2) + 'px' }); } $(document).ready(setPosition); 

However, this does not work.
because $ ('# image'). width () returns 28px before it is loaded in IE8 (by the way, IE7 was great)

So I finally tried the waitForImages jQuery plugin for example

 $(document).ready(function() { $('#image1').waitForImages(function() { setPosition(); // without inspectSize() }); }); 

It works great with cached images, but it doesn't work with non-cached images.
The function is called before Image1 has a width and a height.


What should I do?

+4
source share
3 answers

You can simply bind the repositioning callback to the load event handler.

So in the last example:

 $('#image1').load(function() { setPosition(); // without inspectSize() }); 

Where #image1 points to your image tag. Alternatively, since you mention that #image1 might just be a container, then:

 $('#image1 img').load(function() { setPosition(); }); 

The jfriend00 update makes a good point below, since "loading" will only start when an image is added to the DOM, and not if it already exists on the page when your JavaScript starts.

To get around both scenarios, you can do this:

 var img = $('#image1'); if (img.prop('complete')) { setPosition(); } else { img.load(function() { setPosition(); }); } 

Checking prop('complete') will return true if the image already exists and if it does not bind to the load event handler.

+6
source

a simple example is to associate a load event with an image. I always do the following

 <img data-src="image.jpg" /> 

Note that I have not set the src attribute yet

 $(function() { $("img").each(function() { $(this).load(function() { alert('ready to call $(this).width()'); }).prop("src", $(this).prop("data-src")); }); }); 

.prop("src", $(this).prop("data-src")); install new src after booting boot event

+1
source

Try writing the same code inside.

 $('window').load(function() { // Your code here.. }); 
+1
source

Source: https://habr.com/ru/post/1387698/


All Articles