Thursday, January 01, 2009

Using JavaScript to check if an image is loaded

I had an interesting problem the other day. The project I'm on is a real estate listing website. It's very Web 2.0, using AJAX calls to provide the user with a rich experience. We use the Prototype Library for all our AJAX calls and DOM manipulation.

So the problem came about with the enlarged photo browsing portion of the site. Each listing has at least one photo associated with it. If the listing has more than one photo, then the user can browse through the photo with simple NEXT & PREVIOUS links. Under the scene, when the user presses one of the links we make a simple AJAX call to load the next image and swap out the div the image belongs to.

The problem came about when we were testing in IE. The footer would sometimes appear right over the image. IE wasn't recognizing that one of the div elements was supposed to grow to match the size of the image inside it. The simple fix was to set the Height of the problem div to the Height of the child div that is holding the image. To do this all I had to do was call this method in the "onComplete" section of my AJAX call.

This worked in most cases but there were still times when the footer tag would appear in the middle. With the help of firebug lite, and Nate Young, I realized that my method was being called before the image was finished loading. The solution was loading the image and checking the "complete" on the image object. If the image isn't finished, just make a simple recursive call.



function moveFooter(){
if ($('enlargedImageDiv') && $('imageContainer')){
var image =
new Image($('imageContainer').siblings[0]);
if(image.complete) {
Element.setStyle($('enlargedImageDiv'), {
height:$('imageContainer').getHeight()+41
});
}else{
moveFooter()
}
}
}

1 comment:

Unknown said...

using javascript to check if an image is loaded nice posts..

Hadoop training in hyderabad.All the basic and get the full knowledge of hadoop.
hadoop training in hyderabad