user1223654 user1223654 - 1 year ago 59
HTML Question

jquery .height() is not returning the real value after the append function just called

I am trying to vertically align middle some pics using jquery.

Here is my code

$(".scroll a").hover(function (evt) {
$("#box a").empty().append(
$('<img src='+this.href+' class="loadimg">')

while the vertical align function is here

function vertical_align(){
var child = $(".loadimg").height();
var parent = $("#box").height();
var margin = (parent - child)/2;
$("#box a").children("img").css('margin-top', margin);

Now the problem i am facing is that when the page is loaded, the
gives zero and the margin of the pic becomes half of the parent height which mean that
is returning zero. But this only happens for the first time hover on each image.


this happens probably because you're reading the height too early, when at the first request the image isn't fully loaded. You should wait the load (or complete, from the 2nd request of the same image) event for the image, like so

$(".scroll a").hover(function (evt) {
     var node = $("#box a");
     $('<img src='+this.href+' class="loadimg">')
       .one('load complete', function() {