MadhuB
MadhuB

Reputation: 97

JQuery- add css for each img element having a class

$(document).ready(function() {
    $("img.resizeImage").each(function(){
        var img = $(this); 
        var width = $(this).width();    // Current image width
        var height = $(this).height();  // Current image height
       // alert("give image size ....."+width+", "+height);
        var pic_real_width, pic_real_height;
        $("<img/>").attr("src", $(img).attr("src"))
            .load(function() {
                pic_real_width = this.width;  
                pic_real_height = this.height; 

            });

        if(pic_real_width < width  ){
            //alert("display original width.sssss 103..");
            $(this).removeAttr("width");
            $(this).css("width",pic_real_width);
        }

        if( pic_real_height < height ){
            //alert("display original height ss.102..");
            $(this).removeAttr("height");
            $(this).css("height",pic_real_height);
        }
    });
});

in above jquery execution flow is not hitting last if conditions. I am not acquiring desired result. If I keep some alert above the two if()s then execution flow goes inside two if conditions. pl help me . How can execute jquery statements line by line..

Upvotes: 0

Views: 802

Answers (1)

Alnitak
Alnitak

Reputation: 339816

Your image loading is asynchronous, which means that the .load callback won't be called straight away.

Hence pic_real_width and pic_real_height are unknown at the point you try to use them.

Perhaps you should move those two conditions into the callback function?

Upvotes: 3

Related Questions