Incorrect image properties search on boot

A curious problem. I have a set of images with some attributes that I would like to use in a div (as a caption). Using each, I want to get the width of the image (and some other properties) in order to correctly align the dynamically generated div (like the caption of the image).

img = $('img') img.each(function(index){ var width = $(this).width(); console.log(width); // other properties $('<div class="caption">Some text</div>').insertAfter($(this)); $(this).next().css({ 'width': width // other properties }); 

However, sometimes $ (this) .width () gets the correct value, other times it gets 0. This is especially good when the press returns in the direction bar, but not when I press Ctrl + R, but only in Chrome. It does not work the same in all browsers, so this is a mess. I thought JQuery was trying to get width () before loading the image, so I am moving my code to document.ready (function () {}) instead of (function () {}) (), but it does not work anyway.

What could be? As a reference, these are the styles applied to images:

 display: block; padding: 4px; line-height: 1; max-width: 100%; margin-left: auto; margin-right: auto; 

So, I would like to get the calculated width (which, as far as I know, should be obtained .css (), but not sequentially in this case).

Hi

+4
source share
2 answers

Most likely, the images will not be fully loaded all the time when you run this code. Be sure to download images first.

 function imgDone(){ var width = $(this).width(); console.log(width); // other properties $('<div class="caption">Some text</div>').insertAfter($(this)); } $('img').each(function(index){ if (this.complete || this.readyState = 4) imgDone.apply(this); else $(this).load(function(){ imgDone.apply(this); }); }); 
+2
source

jQuery will not wait for images in $(document).ready() .
Try $(window).load() instead, as indicated in example 5 here

+3
source

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


All Articles