Resize image with jQuery to fit the div
By Anatoly Mironov
There are many interesting jQuery plugins for resizing and cropping of images. Among them are jrac and image scale. I have tested the latter: It works very fine
$(window).load(function() {
var $imgContainer = $("#layout-news-image");
var $newsImg = $("#layout-news-image img\[rel!='sp\_DialogLinkIgnore'\]");
$imgContainer.css("width", $imgContainer.parent().width());
if ($newsImg.length > 0) {
if ($newsImg.width() < $imgContainer.width()) {
$imgContainer.width($newsImg.width());
}
if ($newsImg.height() < $imgContainer.height()) {
$imgContainer.height($newsImg.height());
}
$newsImg.imgscale({
parent : '#layout-news-image',
center: "true",
scale: "fill"
});
}
});
```This script checks if the original image is lesser than container div and doesn't resize if it is so. **#layout-news-image img\[rel!='sp\_DialogLinkIgnore'\]** means that do not resize if there is a hidden image with rel="sp\_DialogLinkIgnore". See the [jQuery selectors](http://api.jquery.com/category/selectors/) for more info. This script can be improved by adding window resize event in javascript. I use **$(window).load** instead of the usual _$(document).ready_ because [ready-function in jQuery runs when DOM is loaded, if the page is not cached it happens before the image is loaded](http://web.enavu.com/daily-tip/daily-tip-difference-between-document-ready-and-window-load-in-jquery/). $(document).ready doesn't work.
## Comments from Wordpress.com
####
[sdfsdf](http://sdsdfsdf "sdfsdf@ssdf.sdd") - <time datetime="2012-06-28 19:28:51">Jun 4, 2012</time>
doesn't work: it's just squeeze the picture. No examples included == no possibility to check.
<hr />
####
[Anatoly Mironov]( "mirontoli@gmail.com") - <time datetime="2012-11-05 10:06:01">Nov 1, 2012</time>
Thank you Alejandro for the awesome js lib and sharing it. I will absolutely recommend it.
<hr />
####
[Alejandro Emparan (@krc_ale)](http://twitter.com/krc_ale "krc_ale@twitter.example.com") - <time datetime="2012-11-02 20:21:55">Nov 5, 2012</time>
I wrote a jQuery plugin for that: https://github.com/karacas/imgLiquid
<hr />