Curious problem. I have a set of images with some attributes that I’d like to use in a div (as a caption). Using each, I want to get the width of the image (and some other properties), to align the dynamically generated div properly (as a 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 right value, other times gets 0. It’s particularly well behaved when a press return in the direction bar but not when I press Ctrl+R but only in Chrome. It doesn’t work the same in all browsers, so it’s a mess. I thought that Jquery was attempting to retrieve width() before the image was loaded, so I wrap my code in document.ready(function(){}) instead of (function(){})() but it doesn’t work either way.
What could be happening?. Just as a reference, these are the styles applied to the images:
display: block;
padding: 4px;
line-height: 1;
max-width: 100%;
margin-left: auto;
margin-right: auto;
So I’d like to get the computed width (which, as far as I know, should be retrieved by .css(), but in this case, not consistently).
Regards
More than likely the images aren’t completely loaded all the time when you run that code. Try ensuring that the images are done loading first.