views:

351

answers:

3

I'm making an Ajax call which returns me some info including an image path. I prepare all those informations in my HTML which will be displayed as a kind of popup. I just toggle the visibility of by popup div from hidden to visible.

To set the position of my popup div, I have to calculate depending on the height of the image. So, I have to wait for the image to load to know its dimension before setting position and switching visibility to visible.

I tried tricks with recursion, setTimeout, complete img property, while loop... without success.

So, how can I do this. Maybe I should return dimensions in my Ajax call.

A: 

You can use jQuery load event.

Have a look at the example:

$('img.userIcon').load(function(){
    if($(this).height() > 100) {
        $(this).addClass('bigImg');
    }
});
Sagi
-1: no mention of jQuery in the question, so an answer like this can be quite confusing.
Andy E
Please don't use jquery unless jquery is requested
Juan Mendes
+2  A: 
var img = new Image();
img.onload = function() { alert("Height: " + this.height); }
img.src = "http://path/to/image.jpg";
Josh Stodola
+1 - This is what I would have posted.
Andy E
Grat! BTW: i'm quite ignorant on the AJAX subject, but just in case an image got with AJAX is cached in the same way of an image written dierctly into HTML code, you could eventually add this in order to avoid browser's image caching (obviously only if you need it): img.src="http://path/to/image.jpg"+"?refresh="+new Date().getTime();
Marco Demajo
@Marco Or set `cache: false` on the XHR :) Although I don't think it's relevant here because the AJAX call is returning a URL to the image, not the image itself. But yes I suppose he could still use a random query string value to make sure no user-agent caching occurs.
Josh Stodola
A: 

Check this YUI image loader it will be helpful i think.

Anil Namde