javascript - Compute div style only when it completes rendering an image -
in script loading image array div, calculate style elements tuned. problem works if use timeout function before calculating styles, this:
$('#forecastimg').attr('src',get_imageitemlocation(imagearray[0])); settimeout(function(){ var himg= $("#forecastimg").height(); var hest = $("#esterno").height(); var margin= ((hest-himg)/2)-$(".header").height()-$(".forecastdate").height(); if (margin>0){ $("#forecastimg").css('margin-top',(margin+'px')); } },240);
how can rid of timeout , sure height()
value correct? if remove timeout, alwyas height()=0
value.
well problem here image not loaded when you're trying calculate margin, that's why $('#forecastimg').height()
not returning expected height when try make calculations right away (in case, you're doing wait loading a settimeout
)
however, can use $().load
method instead of unreliable settimeout
consistently run calculations after loading of image. that, must first bind .load
callback method calculations and then change src
value of it, otherwise image might load without calling our .load
callback:
$('#forecastimg') .one('load', function () { var himg = $("#forecastimg").height(), hest = $("#esterno").height(), margin = ((hest-himg) / 2) - $(".header").height() - $(".forecastdate").height(); if (margin > 0) { $("#forecastimg").css('margin-top',(margin+'px')); } }) .attr('src', get_imageitemlocation(imagearray[0]));
Comments
Post a Comment