Nathan
Nathan

Reputation: 7032

jQuery: Function bound to image's onload fetches old height() info

I've got a function bound (in the HTML) to an image's onload="". The function uses jQuery's height() method to find the height of the image, which is used to center it vertically. Code below.

The context is a slideshow of images with different dimesions, where the src="" of the <img> is changed as the user selects the next image. The bound function is successfully called every time the source changes, but the number it pulls with height() is old: that of the image before its source changed. In other words: When I start at the first image, the height() is right. When I go to the second the height is the same as before even though it should be different. When I go to the third image, the height is that of the second image. And so on. I know that it can fetch the height: If I call this function with another element's onclick once I'm sure the image has loaded, it works fine.

How can I make sure that the height() info my function grabs is current, i.e. that of the image as it is now? I know this isn't a problem with downloads or speed; I'm testing locally.

Many thanks in advance!

Code:
HTML for image:

<img class="slidePhoto" id="slideImage" src="img1.jpg" onload="centerImg()" />

Relevant part of JS for centerImg():

function centerImg(){
    var offset = Number(($('#slideImage').height())/2*-1);
    $('.slidePhoto').css({'top': '50%', 'margin-top': offset});
}

Upvotes: 0

Views: 569

Answers (3)

ndp
ndp

Reputation: 21996

I believe that since you've set the height explicitly on the element, that's what you're getting when you ask for the height the next time. A couple options:

  • (I'd try this) Create a new Image outside the DOM (var i = new Image(); i=src='...) and read the size from that (i.height). That should provide you with an accurate height (although some cross-browser testing will be necessary).
  • In your load function you could try setting the height to "auto" before measuring it. Not sure if this will help.
  • Just create a new <img> tag and replace the current one with this.

One of these should work.

Upvotes: 1

Chris W.
Chris W.

Reputation: 39189

You should use jQuery to setup the load event. I believe this is what you are looking for.

$('img.slidePhoto').load(function() {
    var offset = $(this).height()/2*-1;
    $(this).css({'top': '50%', 'margin-top': offset})
}

(FYI: That should go in your $(document).ready() method.)

See the jQuery documentation for the .load() method.

Upvotes: 0

Zach Green
Zach Green

Reputation: 3460

If the image source is changing with a button click, could you tie a jquery click event handler to the button to change the image, and then pull the height rather than trying to pull the height in the "onload" event of the image tag? jQuery Click Event

Upvotes: 1

Related Questions