views:

34

answers:

1

Hello

I'm trying to center a new image vertically in a div after changing the src using attr in this way:

$("#image").attr("src",newsrc);
var height = $("#image").height();
var newmargin = (divsize - height)/2;
$("#image").css=("margin-top",newmargin);

it always uses the height of the previous image. is it a timing thing? do i need to bind getting the new height to something to prevent it prematurely grabbing the (previous images) height?

all images are preloaded on the loading of the page...

A: 

do i need to bind getting the new height to something to prevent it prematurely grabbing the (previous images) height?

Kinda. load event should work.

$("#image").attr("src",newsrc);
$('#image').load(
    function() {
        var height = $("#image").height();
        // ...
    }
);

http://api.jquery.com/load-event/

Nikita Rybak
Tried.. Still only getting the previous images height.
minikomi
@minikomi Here's a working example http://jsfiddle.net/pLFCd/1/
Nikita Rybak
interesting.. thankyou for taking the time to make this. It's working! Except when you press the button for the displayed image and then the alternate image button - it gives the previous images height in chrome. Safari and firefox give the correct response. Maybe this is what I was seeing. Interesting. EG. set to yahoo -> press 1 for no image change -> press 2 expect: 95result: 50
minikomi
.load won't always fire in all browsers, especially if the image is cached. One simple tip if you don't care about caching the image when it SHOULD be cached is to add a random querystring to the src. somepic.jpg?[timestamp]
ScottE