Selenir
Selenir

Reputation: 718

JQuery variable in function strange behavior

I was working on script which resizes images to fit container size. I wrote down the following code:

$(function () {
    $('.postbody .content img').each(function () {
        var containerWidth = $(this).parent().width();
        if ($(this).width() > containerWidth) {
            $(this).width(containerWidth);
            $(this).wrap('<a href="' + $(this).attr('src') + '" target="_blank"></a>');
        }
    });
});

But it only worked for the first element in loop. With my previous experience with issues following assigning jQuery methods to a variable I changed the code a bit:

$(function (){
    $('.postbody .content img').each(function () {
        if ($(this).width() > $(this).parent().width()) {
            $(this).width( $(this).parent().width() );
            $(this).wrap('<a href="'+$(this).attr('src')+'" target="_blank"></a>');
        }
    });
});

And now it works perfectly. But I cannot figure out how. Shouldn't the containerWidth variable get new value with each function call by the each loop?

EDIT: Please note that all containers are equal size.

Upvotes: 2

Views: 67

Answers (1)

Kamlesh Suthar
Kamlesh Suthar

Reputation: 172

Try this,

$(function () {
    $('.postbody .content').each(function () {
        var containerWidth = $(this).width();
        var img = $(this).find("img");
        if (img.width() > containerWidth) {
            img.width(containerWidth);
            img.wrap('<a href="' + img.attr('src') + '" target="_blank"></a>');
        }
    });
});

Or You can perform same operation simply with CSS

just make img tag max-width to 100%

Ex.

img {
   max-width: 100%;
}

Upvotes: 2

Related Questions