I'm trying to write a jQuery function that will resize a set of images according to a specified area, rather than simply a max height or width.
There's a similar question here: resize image by area, but I'd like to get it working in jquery and with multiple images at the same time
Here's what I'm currently working with: http://jsfiddle.net/szSE5/21/ — it's not functioning the way I intended at the moment.
How about this:
jQuery.fn.resizeImgByArea = function(avgDimension){
var $this = $(this),
oldW = $this.width(),
oldH = $this.height(),
RatiO = new Number(oldW/oldH),
newH = new Number(Math.round(Math.sqrt(avgDimension/RatiO))),
newW = new Number (Math.round(newH * RatiO));
$this.css({
width: newW + 'px',
height: newH + 'px'
});
}
$(document).ready(function() {
$('#images img').each(function(){$(this).resizeImgByArea(10000)});
});
In your fiddle: http://jsfiddle.net/szSE5/21/
jQuery.fn.resizeImgToArea = function(area) {
this.each(function() {
var imgElement = $(this);
var originalWidth = imgElement.width();
var originalHeight = imgElement.height();
var aspectRatio = originalWidth / originalHeight;
var newHeight = Math.round(Math.sqrt(area/aspectRatio));
var newWidth = Math.round(aspectRatio * newHeight);
imgElement.width(newWidth);
imgElement.height(newHeight);
});
return this;
};
At first glance, your jsfiddle solution is not working because "this" in your context is a straight-up DOM element, not a jQuery object.