views:

648

answers:

3

Hello,

I have a div with width 600 px. I want to pull the images dynamically. Images size are varies. What I want to do is, if the image size is more than 600 px, we will resize the image to 600 px to fit into the div. But if the image is not more than 600px, we will leave as original image width.

How can i achieve that by using jquery ? Thanks.

+3  A: 

You may be able to do this without any JavaScript by giving the image no explicit width (so it will use the original width) and adding the following CSS property:

<img style='max-width: 600px' src='...'>

Caveat: Doesn't work in IE 6. Compatibility table

Pekka
thanks, i will try this
spotlightsnap
thanks it works
spotlightsnap
You might see problems with this in certain browsers when not giving an image an explicit width. Especially if you try to use some popular jQuery plugins. But maybe with your application that doesn't apply. +1 for the answer.
jeerose
A: 

You can use css to set the width of the image to 100% and then keep the aspect ratio using jQuery like this:

$('#containerDiv img').width(); //gets width of image
$('#containerDiv img').height(); //gets height of image

You can make a calculation to keep the aspect ratio and then use the height() property to set the new height of the image.

jeerose
thanks, i gonna try this
spotlightsnap
A: 

If you are hosting those images you might want to scale them on the server when they get there. That way you'll save bandwidth, lower download time for the browser and don't need to resize on client side.

MyGGaN