- Image should be resized down to fit the size of its parent
- Image shouldn't be stretched larger than its original dimensions
- Image should still exist in document flow, no position: absolute
- Aspect ratio must be preserved
So, I wrote my own, from scratch.
// doResize, by Ben Fisher
// requires jQuery
var marginH = 100, marginW = 100;
function doResize() {
var availh = $(window).height();
var availw = $(window).width();
availh = Math.max(10, availh - marginH);
availw = Math.max(10, availw - marginW);
if (truew > availw || trueh > availh) {
var factor = Math.min(availw / truew, availh / trueh);
$('#targetimage').css('width', Math.round(truew * factor));
$('#targetimage').css('height', Math.round(trueh * factor));
}
else {
$('#targetimage').css('width', truew);
$('#targetimage').css('height', trueh);
}
}
// after the image loads, call doResize, could look like
$('#featuredimage').load(function() { doResize(); });
// register to respond to any subsequent resize events with
// $(window).resize(function(){ doResize(); });
// truew and trueh can either be set in advance, or read once the image loads
I'm using this code to show a gallery for the digital art I've been working on.