casraf
casraf

Reputation: 21684

Image on load resize

I have a list of divs that contain images, and I want to make sure they're at proper size. For this, they're usually 100% width, unless they're smaller than the parent's 100%, in which case they should be at their original size. Here's my code:

$('.sa-img').each(function() {
    img = new Image();
    var obj = $(this);
    img.onload = function() {
        //console.log(this.width + ' <= ' + obj.outerWidth());
        if (this.width <= obj.outerWidth())
            obj.css({'width':this.width +'px'});
        }
        img.src = $(this).attr('src');
    }
});

As for the HTML, it's about as simple as this:

<div class="sa-img-container">
    <img class="sa-img" src="<?=$img_url?>" />
</div>

Now this works fine and dandy, except for the first image. What do I do about it? It's as if it's not waiting for it to load or something. It doesn't matter if I rearrange the images, it's always the first one to suffer. The output for its original size is always 100, which causes it to resize to the image's original size regardless of the fact it's larger than the 100% (say an image of 220px, would resize to 220px instead of 100%, inside a 204px div - causing the layout to not work as expected.

Upvotes: 0

Views: 2421

Answers (1)

ahren
ahren

Reputation: 16961

As in the comments above, this is quite easily achieved using CSS. Specifically, the max-width property.

Assuming the width of the image is 600 pixels, you could have:

.resize-to-100{
    width: 500px;
    background: red;
}
.dont-resize{
    width: 750px;
    background: yellow;
}
img{
    max-width: 100%;
}

Example: http://jsfiddle.net/efbVZ/

Upvotes: 1

Related Questions