user1223654
user1223654

Reputation: 99

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">')
  );
  vertical_align();
});

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 imageHeight gives zero and the margin of the pic becomes half of the parent height which mean that imageheight is returning zero. But this only happens for the first time hover on each image.

Upvotes: 0

Views: 1030

Answers (1)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

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");
     node.empty(); 
     $('<img src='+this.href+' class="loadimg">')
       .appendTo(node)
       .one('load complete', function() {
           vertical_align();
       });

});

Upvotes: 2

Related Questions