2

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.

7
  • Yeah it will get updated. But not if that particular code runs before the page got loaded. Commented Aug 12, 2015 at 12:49
  • it should work, can you create the issue in a demo.. only thing is you might have to wait for the image to get loaded Commented Aug 12, 2015 at 12:50
  • 1
    jsfiddle.net/arunpjohny/594e3ghn Commented Aug 12, 2015 at 12:53
  • The above script will work fine on $(window).load() event. As by that time all the images are loaded. Hence the parent div gets it width. I think the issue is with the event and not with the variable. Commented Aug 12, 2015 at 12:54
  • jsfiddle.net/arunpjohny/594e3ghn/3 Commented Aug 12, 2015 at 12:57

1 Answer 1

2

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%;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.