javascript - Unreliable retrieval of properties in images when loading -
curious problem. have set of images attributes i'd use in div (as caption). using each, want width of image (and other properties), align dynamically generated div (as caption of 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, $(this).width() gets right value, other times gets 0. it's particularly behaved when press return in direction bar not when press ctrl+r in chrome. doesn't work same in browsers, it's mess. thought jquery attempting retrieve width() before image loaded, wrap code in document.ready(function(){}) instead of (function(){})() doesn't work either way.
what happening?. reference, these styles applied images:
display: block; padding: 4px; line-height: 1; max-width: 100%; margin-left: auto; margin-right: auto; so i'd computed width (which, far know, should retrieved .css(), in case, not consistently).
regards
more images aren't loaded time when run code. try ensuring images done loading 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); }); });
Comments
Post a Comment