russjman
russjman

Reputation: 506

Jquery dynamic image resizing not taking correct image dimentions

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;
        });


    });

Upvotes: 2

Views: 753

Answers (2)

Pointy
Pointy

Reputation: 413727

See this older stackoverflow question: 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.

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532465

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':''}); 

} 

Upvotes: 2

Related Questions