tags:

views:

97

answers:

2

For some reason while clicking around this gallery i'm creating, the dimensions that get assigned to the CSS don't always take when a new image gets loaded in the .product-image container. I think it's caused by assigning css attributes while an image is still loading, as it only seems to happen with larger images. Once ".more-views a" is clicked again, the correct dimentions are calculated.

function loadNewImage(newurl) {

        jQuery(".col-main .product-image a").attr("href",newurl);
        jQuery(".col-main .product-image img").attr("src", newurl);
        jQuery(".col-main .product-image img").css({'width': '','height':''});

    }

    function resizeImageByAspect(ele) {
        var maxWidth = 465;
        var maxHeight = 436;
        var ratio = 0;
        var width = ele.width(); 
        var height = ele.height();
        ele.css("width", width);
        ele.css("height", height);

        if (width > maxWidth) {
            ratio = maxWidth / width;
            ele.css("width", maxWidth);
            ele.css("height", height * ratio);
            height = height * ratio;
            width = width * ratio;
        }

        if (height > maxHeight) {
            ratio = maxHeight / height;
            ele.css("height", maxHeight);
            ele.css("width", width * ratio);
            width = width * ratio;
        }
    }
    jQuery(document).ready(function(){
        resizeImageByAspect(jQuery(".col-main .product-image img"));

        jQuery(".more-views a").click(function(event){
            jQuery(".col-main .product-image img").fadeOut("fast", function(){


                loadNewImage(jQuery(event.target).parent().attr('href'));

                resizeImageByAspect(jQuery(".col-main .product-image img"));
            }).delay(500);

            jQuery(".col-main .product-image img").fadeIn("fast");
            return false;
        });


    });
+2  A: 

I'd suggest adding a load handler on the image before setting the new src attribute. Have this load handler run your resize code.

function loadNewImage(newurl) { 

    jQuery(".col-main .product-image a").attr("href",newurl); 
    jQuery(".col-main .product-image img").unbind('load').load( function() {
         resizeImageByAspect($(this));
    }).attr("src", newurl); 
    jQuery(".col-main .product-image img").css({'width': '','height':''}); 

} 
tvanfosson
Thx man!. There still seems to be a delay on new height and width css taking to the new image. I moved the height width css reset into the call back function for load(), and changed to fade in "slow". Now it smoof like butta
russjman
A: 

See this older stackoverflow question: http://stackoverflow.com/questions/821516/browser-independent-way-to-detect-when-image-has-been-loaded

Wade through those comments, and then decide if you want to try and use an event handler to watch for the completed loading of your images before you do the size adjustment.

Pointy